Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java write/append to each line of a text file

807599Apr 20 2007 — edited Apr 20 2007
I have spent numerous hours trying to figure out what I am doing wrong. If anyone more experienced could tell me what is wrong with my code.

I have a very simple text file with 5 lines:

line1
line2
line3
line4
line5

All I am trying to do is append some string to the end of each of those lines. Everytime I run my code, it erases all content but does not write/append anything to the file. Any help is greatly appreciated.
Thanks! I am about to throw this monitor out the window!!
package Chapter6;

import java.io.*;

public class fileNavigation2 {


	public static void main(String[] args) {
	
		File dir = new File("C:\\testing");
		System.out.println(dir.isDirectory());
		
		
		try {
			File file = new File(dir, "Test.txt");
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			
			String s = "Add1,";
			String s2 = "Add2\n";
			String str;
			
			while((str = br.readLine()) != null) {
			StringBuffer sb = new StringBuffer(str);
			sb.append(s + s2);
			String y = sb.toString();
			System.out.println(sb);
			System.out.println("Appending");
			bw.write(y);
			}
			
			bw.close();
			System.out.println("Done");
			
			
		}catch(IOException e) {}
		
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 18 2007
Added on Apr 20 2007
5 comments
7,094 views