views:

36

answers:

2

i want to read a file one character at a time and write the contents of first file to another file one character at a time.

i have asked this question earlier also but didnt get a satisfactory answer..... i am able to read the file and print it out to std o/p.but cant write the same read character to a file.

A: 

You can read characters from a file by using a FileReader (there's a read method that lets you do it one character at a time if you like), and you can write characters to a file using a FileWriter (there's a one-character-at-a-time write method). There are also methods to do blocks of characters rather than one character at a time, but you seemed to want those, so...

That's great if you're not worried about setting the character encoding. If you are, look at using FileInputStream and FileOutputStream with InputStreamReader and OutputStreamWriter wrappers (respectively). The FileInputStream and FileoutputStream classes work with bytes, and then the stream reader/writers work with converting bytes to characters according to the encoding you choose.

T.J. Crowder
I wouldn't advise FileReader and FileWriter personally - they don't let you specify the encoding to use.
Jon Skeet
@Jon: Good point, though in this case I think encodings are probably going to get a bit beyond where the OP is right now.
T.J. Crowder
+1  A: 

It may have been useful to link to your previous question to see what was unsatisfactory. Here's a basic example:

public static void copy( File src, File dest ) throws IOException {
    Reader reader = new FileReader(src);
    Writer writer = new FileWriter(dest);

    int oneChar = 0;
    while( (oneChar = reader.read()) != -1 ) {
        writer.write(oneChar);
    }

    writer.close();
    reader.close();     
}

Additional things to consider:

  • wrap reader/writer with BufferedReader/Writer for better performance
  • the close calls should be in a finally block to prevent resource leaks
wolfcastle