Home > Java > javaTutorial > body text

File I/O using character streams

Susan Sarandon
Release: 2024-11-12 20:54:02
Original
427 people have browsed it

I/O de arquivo com o uso de fluxos de caracteres

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

Copy after login
  • filename: Indicates the full path of the file.
  • include: Defines whether the writing will be added to the end of the file (true) or whether it will overwrite the existing file (false).

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);
    }
  }
}

Copy after login

In this example:

  • BufferedReader reads lines of text from the console.
  • FileWriter writes the text to the file "test.txt", adding a new line after each entry.
  • Stop condition: When user enters "stop", recording stops.

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template