Reputation: 19612
I am trying to create a file and keep on appending into that file. In my code file is getting created but It is not appending anything in that file. Don't know why? Can anyone suggest me what wrong I am doing..
Updated Code:-
File file =new File("D://GeoData1.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
int j = -1;
while(true) {
j++;
String ipAddress = generateIPAddress(j);
try {
out.write(ipAddress);
System.out.println(ipAddress);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 2
Views: 622
Reputation: 454
If you want to see the changes made to the file during the time the program is running you need to flush the writer. Please note that sooner or later it will be flushed automatically. The reason why you don't see changes in your text editor depends on your editor. For instance it is not able to open such big file (please note that in your program you are appending chars to this file very fast). Check the size of the file. If the size is increasing then it works.
If you want to monitor the file you can use tools like tail.
Upvotes: 0
Reputation: 22461
Are you closing the writer?
finally {
bufferWritter.close();
}
Update:
If you are using Java 7, try this:
final int NUMBER_OF_IPS_TO_APPEND = 5000; // or whatever size
Charset charset = Charset.defaultCharset();
Path file = Paths.get("myfile.txt");
try (BufferedWriter writer = Files.newBufferedWriter(file, charset,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND)) {
for (int i = 1; i <= NUMBER_OF_IPS_TO_APPEND; i++) {
String ip = generateIPAddress(i);
System.out.printf("Generated ip: %s\n", ip);
writer.append(ip + "\n");
}
} catch (IOException x) {
System.err.format("IOException: %s\n", x);
}
Code adapted from The Java Tutorials.
Check if the IPS are being printed to the console and the file.
Fully working code with a mock implementation of generateIPAddress
. It appends 5000 random IPv4 addresses (not checking for validity) to myfile.txt
everytime it is executed.
Upvotes: 2
Reputation: 4919
You have infinite loop with while(true). You should make a break point with a statemant or make the the "while" loop like while(i < xy)....
Upvotes: 1
Reputation: 3128
I would try just passing the file writer the file object and getting rid of the .getName()
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
Upvotes: 1
Reputation: 1991
First of all, the loop is never-ending. You should at least make it stop at some point. Also, you need to close the file to free any memory. Hope it helps!
--edit-- To close a file, its
file.close();
Upvotes: 0