Java IO 流:字节流、字符流、接口、实现类与阻塞方法
Java IO流提供了多种字节和字符流类,用于读写数据到文件、网络或其他数据源。
字节流:
InputStream
FileInputStream
BufferedInputStream
OutputStream
FileOutputStream
BufferedOutputStream
字符流:
Reader
InputStreamReader
BufferedReader
Writer
OutputStreamWriter
BufferedWriter
这里是一个简单的字节输入流示例,用于从文件中读取数据:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileReadExample {
public static void main(String[] args) {
String filePath = "example.txt";
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
int byteContent;
while ((byteContent = inputStream.read()) != -1) {
System.out.print((char) byteContent);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
对于字符输出流,以下是写入字符到文件的示例:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class FileWriteExample {
public static void main(String[] args) {
String filePath = "example.txt";
OutputStream outputStream = null;
Writer writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = new OutputStreamWriter(outputStream);
writer.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上代码展示了如何使用FileInputStream
和FileOutputStream
读取和写入文件,并使用OutputStreamWriter
和InputStreamReader
在字节和字符之间转换。在实际应用中,你可能会发现使用BufferedInputStream
, BufferedOutputStream
, BufferedReader
, 和 BufferedWriter
提供了更好的性能,尤其是在处理大量数据时。
评论已关闭