Reputation: 2617
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.
Upvotes: 0
Views: 1651
Reputation: 5930
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:
Upvotes: 2
Reputation: 1074168
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.
Upvotes: 0