import java.io.*;
import java.io.IOException;

public class ReadWriteFile{
	static File f1 = new File("C:\\source.txt");
	static File f2 = new File("C:\\dest.txt");
	
	public String readFile() throws IOException
	{
		String msg = "";
		
		FileReader fr = new FileReader(f1);
		BufferedReader br = new BufferedReader(fr);
		msg = br.readLine();
		System.out.println(msg);
		fr.close();
		return msg;
		
	}
	
	public void writeFile(String str) throws IOException
	{
		FileWriter fr = new FileWriter(f2);
		BufferedWriter br = new BufferedWriter(fr);
		br.write(str);
		fr.close();
		
	}
}


public class Entry {
	public static void main(String[] args){
		ReadWriteFile f1 = new ReadWriteFile();
		try {
			f1.writeFile(f1.readFile());
		}
		catch(IOException e)
		{
			e.getStackTrace();
		}
		
	}
	
}

What's wrong with this code? I am not getting any output file in the end and no errors nothing..

_______________________________________________________________________
Apart from this What are the best methods to read n write data. Preferably nice tutorial to explain differences between different type of read/write methods. please don't redirect me to sun site.

Recommended Answers

All 3 Replies

Close the bufferedwriter and not the file writer. By closing the filewriter you are probably preventing the bufferedwriter from flushing.

still no use. first question, the data itself from the file is not getting read and surprisingly no error is being thrown.

Then the first line is a blank line (or there are no lines, but then it would print null) and you are only reading one line. Also, if you can't work with the Sun tutorials no other's will help you either. The advice about closing the outer most reader/writer still stands.

Edit: Aack, you also need printStacktrace, not getStacktrace.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.