javaio读取字符、读取字节流demo
下面是一个示例代码,展示了如何使用Java的IO类来读取字符流和字节流:
读取字符流:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CharacterStreamDemo {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个示例代码使用了BufferedReader类来读取字符流。首先创建一个FileReader对象来读取文件,然后将其传递给BufferedReader的构造函数中。通过调用readLine()方法来逐行读取文件内容,直到返回null表示文件读取完毕。
读取字节流:
import java.io.FileInputStream;
import java.io.IOException;
public class ByteStreamDemo {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个示例代码使用了FileInputStream类来读取字节流。首先创建一个FileInputStream对象来读取文件。然后创建一个缓冲区buffer,并使用read()方法来读取字节流到缓冲区中。通过调用System.out.write()方法将缓冲区中的内容输出到控制台,直到read()方法返回-1表示文件读取完毕。
请注意,在使用IO类时,需要在代码中使用try-with-resources语句或手动关闭资源(如文件或流)来确保资源的正确释放
原文地址: https://www.cveoy.top/t/topic/iUkY 著作权归作者所有。请勿转载和采集!