Reputation: 49
In my previous thread I forgot to show people that I had made an attempt to try this myself, rest assured, i have spent the past 2 hours trying to get this stupid problem solved.
I need to do the following :
This is as far as I managed to get :
package science;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
public class DumpData {
static void writeStringToFile(String gender, String securityLevel){
try {
File file = new File(gender + securityLevel + ".txt");
//file.getParentFile().mkdirs();
PrintWriter pr = new PrintWriter(file);
FileInputStream fs = new FileInputStream(gender + securityLevel + ".txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
if (br.readLine() == null) {
pr.println("" + 0);
}
//String first = br.readLine();
//System.out.println(first);
try{
String first = br.readLine();
int num = Integer.parseInt(first);
int add = (num + 1);
pr.println("" + add);
pr.close();
System.out.println(num);
} catch (NumberFormatException e) {
// not an integer!
System.out.println("error");
System.out.println(br.readLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I kept getting this the message "error" printed to the console, and with more examination I found that nothing was being saved to the .txt file at all. I fully expected my code to add 1 to the int in the file every time the method was executed.
Upvotes: 0
Views: 199
Reputation: 209004
You're trying to read a line twice
if (br.readLine() == null) { <-- first time
pr.println("" + 0);
}
//String first = br.readLine();
//System.out.println(first);
try{
String first = br.readLine(); <-- second time
The second time will fail because there is no second line.
Instead just do this
String line;
while ((line = br.readLine()) != null){
int num = Integer.parseInt(line.trim());
...
}
You don't need the first if statement
Upvotes: 1
Reputation: 560
I strongly suggest you to work with Apache COmmons IO when dealing with files.
Here's the link : http://commons.apache.org/proper/commons-io/
Look at the FileUtils class.
Upvotes: 0