简体   繁体   中英

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..... 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM