I store number of text files in the mysql database and need to retrieve them to count each end every program's some features such as "white spaces,num of while loops" etc.
I saved the files in the database with type BLOB. And this is how I retrieve the files. But it prints only the first text file but not all.. The rs.next doesn't work as a loop and show me the other file contents. For first file it works well. Could someone please let me know why this happens?
public class DbPersister {
private Connection conn;
public DbPersister(){
conn=DatabaseConnectionFactory.getConnection();
}
public void getTheFile(){
try {
Statement stmt=conn.createStatement();
String query="SELECT Prog_Num,File FROM file_details";
ResultSet rs=stmt.executeQuery(query);
while(rs.next()){
int prog_num=rs.getInt("Prog_Num");
String file= rs.getString("File");
System.out.println("////////////////////////////////////////"+prog_num+"//////////////////////////////////////////////////////");
FileReader fr=new FileReader(file);
BufferedReader bReader=new BufferedReader(fr);
while(bReader.readLine()!=null){
System.out.println(bReader.readLine());
}
}
} catch (SQLException ex) {
Logger.getLogger(DbPersister.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DbPersister.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And I have taken the file type as string . is it correct. Files could be very large.
Related
I just started with sqlite and I stuck with a strange (maybe just for me) phenomenon. When I connect the testDB.db file in java, and make one or some query, the data and the table itself is disappearing. The consol said that SQL error or missing database, and when I check the database file in cmd, the situation is really that; there is no data in the file. Could anybody help me out with this basic problem? (I suppose that this is just because of the lack of my knowledge in this topic, but I'm open to new information)
public class jdbcTest{
public static void main(String[] strg) {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Username\\Documents\\sqlite\\testDB");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30);
//statement.executeUpdate("drop table if exists person");
ResultSet rs = statement.executeQuery("select * from company");
while (rs.next()){
System.out.print("id = "+rs.getInt("id")+" ");
System.out.println("name = "+rs.getString("name"));
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
finally {
try {
if (connection!=null){
connection.close();
}
}
catch (SQLException e){
System.err.println(e);
}
}
}
}
When opening a nonexistent database file, SQLite will happily create a new, empty one.
The file name you're giving to getConnection does not actually point to the database you saved.
I've create a GUI in Netbeans to get inputs from the user for certain fields. I don't understand how to save the text from the JTextField and Radio Buttons that are selected to a text file.
I attached the picture below of the user form.
Once "OK" button is pressed, the user gets a dialog to save the file.
Currently, I can save the file to a text file. But nothing appears in the text file. How can I retrieve data from each text field and radio button?
Please help, I've tried a lot of solutions but it has not been working properly.
private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String filename = JOptionPane.showInputDialog(null, "Enter the name to be saved", "File Name", 1 );
FileOutputStream writer = new FileOutputStream(filename+".dat");
txtFirstName.getText().toString(); //Trying to get text from First Name field.
writer.close();
JOptionPane.showMessageDialog(null,"Saved Successfully");
}catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Between
FileOutputStream writer = new FileOutputStream(filename+".dat");
and
writer.close();
you should actually write using FileOutputStream's write method.
I think that what you want to do is:
FileOutputStream writer = null;
try {
FileOutputStream writer = new FileOutputStream(filename+".dat");
OutputStreamWriter os = new OutputStreamWriter(writer);
BufferedWriter bw = new BufferedWriter(os);
bw.write(txtFirstName.getText().toString());
} catch (FileNotFoundException ex) {
Logger.getLogger(generafechas.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(generafechas.class.getName()).log(Level.SEVERE, null, ex);
}finally{
if(writer!=null)
try {
writer.close();
} catch (IOException ex) {
Logger.getLogger(generafechas.class.getName()).log(Level.SEVERE, null, ex);
}
}
In the above code you can see that the FileOutputStream (conventionally references as fos for lazyness sake) gets wrapped.
There are two families of classes to write files in Java. Readers/Writers and Streams.
Your fos is a stream, so it deals with system specific implementation and writes bytes or integers, meanwhile that the BufferedWritter (bw for lazyness sake) deals with writing Objects, and basic types. With the wrapping we get the best of both worlds, high level handling and low level functionality.
I'm trying to store a text file in a MySQL database, and when needed, save it to a file.
To save the file, I do:
public void saveFile_InDB(File file)
{
try {
String sql = "INSERT INTO sent_emails (fileName, time, clientName) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, new Date().toString());
statement.setString(2, new Date().toString());
InputStream inputStream = new FileInputStream(file);
statement.setBinaryStream(3, inputStream);
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("File saved sucessfully.");
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
And to retreive and save the file:
public void retrieveFile_fromDB()
{
try {
Statement stmt = (Statement) conn.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM sent_emails WHERE clientName='sally'");
FileOutputStream fos = new FileOutputStream("file.txt");
if (res.next()) {
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
}
} catch (IOException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
} catch (SQLException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
}
}
Storing the file works, but when I try to retrieve and save it, nothing is stored in the output file?
if you want read file from db Mysql
change this part in your code
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
use this code read array of bytes
byte [] bs=res.getBytes("fileName");
fos.write(bs);
it will work
if you return multiple files from db you must declare
FileOutputStream fos = new FileOutputStream("file.txt");
inside while loop and change name of file to avoid overriding
You do not seem to put into the database the things that the column names describe?
fileName and time are for example both set to a timestamp, and clientName is set to the contents of the file. When you later try to select based on clientName, you are actually selecting based on the contents of the file.
Furthermore, when reading the data, you are reading the blob data from the column fileName, but this is wrong because:
fileName contains new Date().toString(), not the contents of the file
fileName should surely contain the file's name, not its contents?
I created an application that uses JSON for the database, and it seems to write fine, and the file reader reads the database fine, but I cant seem to get the database values from the database value.
here is my parsing code:
String userEnteredString = UserEntered.getText();
String userHomeLocal = Tutschedule.userHome;
Reader dataFile = null;
try {
dataFile = new FileReader(userHomeLocal+"/Users/"+userEnteredString+".data");
} catch (FileNotFoundException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
String dbData = dataFile.toString();
try {
JSONObject dbObject = new JSONObject(dbData);
} catch (JSONException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(dbData);
JSONObject dataInfo = new JSONObject(dbData);
String password = dataInfo.getString("password");
System.out.println(password);
BufferedReader buffered = new BufferedReader(dataFile);
String test = null;
try {
test = buffered.readLine();
} catch (IOException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is when I print password it doesnt print anything, leading me to think that the password field is not processed.
here is an example of the database:
{"username":"user","password":"test"}
Thanks!
I don't believe FileReader.toString() is doing what you think it's doing. FileReader inherits toString from object, which means that it is just going to print out the reference, not the contents of the file, and yet you are trying to parse that as JSON. In that case you should have a severe log message though.
In order to read the contents of the file, you should use the read method on the reader or make it easy on yourself and use commons-io FileUtils#readFileToString or something similar.
i'm new to Android and i'm developing an application who is supposed to show a list of places (the class extend activitylist) and when user choose a place it open a new activity with the place details (name, address, phone number, service..).
Actually, i'm looking for a simple way to store those predefined locations details + a simple way to show them later on the app.
Actually, the best solution that i found is:
Save a static file in your application at compile time, save the file in your project res/raw/ directory.
Open the file with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).
InputStream dataIS =
getResources().openRawResource(R.raw.location);
Convert input stream to buffered reader then you can store your data in a Sqlite3 table and use them wherever you want.
public void fillDB(){
InputStreamReader in= new InputStreamReader(dataIS);
BufferedReader dataBR= new BufferedReader(in);
String dataLine;
try {
while ((dataLine = dataBR.readLine()) != null) {
// split the data line
dataLineTokenizer = new StringTokenizer(dataLine, ":");
//SQL query + save data to database
String sql = "INSERT INTO location ...";
//execute query
Log.v("Test Saving", sql);
clubberDB.execSQL(sql);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}