Documentation

The Java™ Tutorials
Hide TOC
Character Streams字符流
Trail: Essential Java Classes
Lesson: Basic I/O
Section: I/O Streams

Character Streams字符流

The Java platform stores character values using Unicode conventions.Java平台使用Unicode约定存储字符值。Character stream I/O automatically translates this internal format to and from the local character set.字符流I/O自动将此内部格式转换为本地字符集,或从本地字符集转换。In Western locales, the local character set is usually an 8-bit superset of ASCII.在西方地区,本地字符集通常是ASCII的8位超集。

For most applications, I/O with character streams is no more complicated than I/O with byte streams.对于大多数应用程序,使用字符流的I/O并不比使用字节流的I/O复杂。Input and output done with stream classes automatically translates to and from the local character set.使用流类完成的输入和输出自动转换为本地字符集,并从本地字符集进行转换。A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer.使用字符流代替字节流的程序自动适应本地字符集,并准备国际化—所有这些都不需要程序员额外的努力。

If internationalization isn't a priority, you can simply use the character stream classes without paying much attention to character set issues.如果国际化不是'首先,您可以简单地使用字符流类,而不必太注意字符集问题。Later, if internationalization becomes a priority, your program can be adapted without extensive recoding.以后,如果国际化成为优先事项,您的程序可以在不进行大量重新编码的情况下进行调整。See the Internationalization trail for more information.有关更多信息,请参阅国际化跟踪。

Using Character Streams使用字符流

All character stream classes are descended from Reader and Writer.所有字符流类都是ReaderWriter的后代。As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter.与字节流一样,有专门用于文件I/O的字符流类:FileReaderFileWriterThe CopyCharacters example illustrates these classes.CopyCharacters示例演示了这些类。

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyCharacters {
    public static void main(String[] args) throws IOException {

        FileReader inputStream = null;
        FileWriter outputStream = null;

        try {
            inputStream = new FileReader("xanadu.txt");
            outputStream = new FileWriter("characteroutput.txt");

            int c;
            while ((c = inputStream.read()) != -1) {
                outputStream.write(c);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

CopyCharacters is very similar to CopyBytes.CopyCharactersCopyBytes非常相似。The most important difference is that CopyCharacters uses FileReader and FileWriter for input and output in place of FileInputStream and FileOutputStream.最重要的区别是CopyCharacters使用FileReaderFileWriter来代替FileInputStreamFileOutputStream进行输入和输出。Notice that both CopyBytes and CopyCharacters use an int variable to read to and write from. However, in CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int variable holds a byte value in its last 8 bits.请注意,CopyBytesCopyCharacters都使用int变量进行读取和写入。但是,在CopyCharacters中,int变量在其最后16位中保存字符值;在CopyBytes中,int变量在其最后8位中保存一个字节值。

Character Streams that Use Byte Streams使用字节流的字符流

Character streams are often "wrappers" for byte streams.字符流通常是字节流的“包装器”。The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes.字符流使用字节流执行物理I/O,而字符流处理字符和字节之间的转换。FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.例如,FileReader使用FileInputStream,而FileWriter使用FileOutputStream

There are two general-purpose byte-to-character "bridge" streams: InputStreamReader and OutputStreamWriter.有两种通用的字节到字符“桥接”流:InputStreamReaderOutputStreamWriterUse them to create character streams when there are no prepackaged character stream classes that meet your needs.当没有满足您需要的预打包角色流类时,使用它们创建角色流。The sockets lesson in the networking trail shows how to create character streams from the byte streams provided by socket classes.网络跟踪中的socket课程演示了如何从socket类提供的字节流创建字符流。

Line-Oriented I/O面向行的I/O

Character I/O usually occurs in bigger units than single characters.字符I/O通常以比单个字符更大的单位出现。One common unit is the line: a string of characters with a line terminator at the end.一个常见的单位是行:一个字符串,末尾有行结束符。A line terminator can be a carriage-return/line-feed sequence ("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n").行终止符可以是回车符/换行符序列("\r\n")、单回车符("\r")或单换行符("\n")。Supporting all possible line terminators allows programs to read text files created on any of the widely used operating systems.支持所有可能的行终止符允许程序读取在任何广泛使用的操作系统上创建的文本文件。

Let's modify the CopyCharacters example to use line-oriented I/O.让我们修改CopyCharacters示例以使用面向行的I/O。To do this, we have to use two classes we haven't seen before, BufferedReader and PrintWriter.为此,我们必须使用两个以前从未见过的类,BufferedReaderPrintWriterWe'll explore these classes in greater depth in Buffered I/O and Formatting.我们将在缓冲I/O格式化方面更深入地研究这些类。Right now, we're just interested in their support for line-oriented I/O.现在,我们只对他们支持面向行的I/O感兴趣。

The CopyLines example invokes BufferedReader.readLine and PrintWriter.println to do input and output one line at a time.CopyLines示例调用BufferedReader.readLinePrintWriter.println一次输入和输出一行。

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;

public class CopyLines {
    public static void main(String[] args) throws IOException {

        BufferedReader inputStream = null;
        PrintWriter outputStream = null;

        try {
            inputStream = new BufferedReader(new FileReader("xanadu.txt"));
            outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));

            String l;
            while ((l = inputStream.readLine()) != null) {
                outputStream.println(l);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

Invoking readLine returns a line of text with the line.调用readLine返回一行文本和该行。CopyLines outputs each line using println, which appends the line terminator for the current operating system.CopyLines使用println输出每一行,println附加当前操作系统的行终止符。This might not be the same line terminator that was used in the input file.这可能与输入文件中使用的行终止符不同。

There are many ways to structure text input and output beyond characters and lines.除了字符和行之外,还有许多方法可以组织文本输入和输出。For more information, see Scanning and Formatting.有关详细信息,请参阅扫描和格式化


Previous page: Byte Streams
Next page: Buffered Streams