JAVA IO流的读写操作
Java IO流提供了多种读写操作的方法,可以根据需要选择适合的方式。下面是一些常用的读写操作示例:
- 使用字节流读写操作:
try (InputStream inputStream = new FileInputStream("file.txt")) {
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
try (OutputStream outputStream = new FileOutputStream("file.txt")) {
String content = "Hello, World!";
byte[] data = content.getBytes();
outputStream.write(data);
} catch (IOException e) {
e.printStackTrace();
}
- 使用字符流读写操作:
try (Reader reader = new FileReader("file.txt")) {
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
try (Writer writer = new FileWriter("file.txt")) {
String content = "Hello, World!";
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
- 使用缓冲流提高读写效率:
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("file.txt"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("file.txt"))) {
String content = "Hello, World!";
bufferedWriter.write(content);
} catch (IOException e) {
e.printStackTrace();
}
这些示例演示了使用Java IO流进行基本的读写操作。根据具体需求,可以选择适合的流和方法进行数据的读取和写入。同时,要注意在读写操作后关闭流资源,以确保资源的正确释放。