Java中IO流的使用,如文件读写实例
在Java中,I/O(Input/Output)流主要用于处理输入和输出数据。以下是一些常见的IO流以及它们的使用实例:
FileInputStream:用于从文件中读取数据。
try {
FileInputStream fis = new FileInputStream("example.txt");
byte[] bytes = new byte[1024]; // 一次性读取1KB
int read = fis.read(bytes);
while (read != -1) { // 如果不为空,继续读取
System.out.print(new String(bytes, 0, read))));
read = fis.read(bytes); // 重新读取数据
}
fis.close(); // 关闭文件输入流
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileOutputStream:用于将数据写入文件。
try {
FileOutputStream fos = new FileOutputStream("example.txt");
String content = "Hello, World!"; // 要写入的字符串
fos.write(content.getBytes()); // 将字符串转换为字节数组,然后写入
fos.close(); // 关闭文件输出流
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader:用于从字符输入流中读取数据。
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("example.txt")))));
String line;
while ((line = br.readLine()) != null) { // 逐行读取
System.out.println(line);
}
br.close(); // 关闭缓冲读流
} catch (IOException e) {
e.printStackTrace();
}
这些实例展示了Java中IO流的基本使用。在实际项目中,根据需求可能会进行更复杂的操作。
还没有评论,来说两句吧...