开发者

reading characters from a file

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...开发者_Python百科.. 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜