Using character streams for file I/O operations in Java is mainly useful for manipulating Unicode text, unlike byte-based streams. Classes like FileReader and FileWriter facilitate this operation with text files.
Using FileWriter
The FileWriter class allows you to create a Writer object to write to files. Its main constructors are:
FileWriter(String nomeArquivo) throws IOException FileWriter(String nomeArquivo, boolean incluir) throws IOException
Below is an example of a simple program that reads lines of text from the keyboard and writes them to a file called "test.txt". Reading continues until the user types "stop".
import java.io.*; class KtoD { public static void main(String args[]) { String str; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter text ('stop' to quit)."); try (FileWriter fw = new FileWriter("test.txt")) { do { System.out.print(": "); str = br.readLine(); if (str.compareTo("stop") == 0) break; str = str + "\r\n"; // adiciona nova linha fw.write(str); } while (str.compareTo("stop") != 0); } catch(IOException exc) { System.out.println("I/O Error: " + exc); } } }
In this example:
Using FileWriter with BufferedReader simplifies writing text and manipulating data in files, especially in continuous and internationalized text operations.
The above is the detailed content of File I/O using character streams. For more information, please follow other related articles on the PHP Chinese website!