Java中的IO流操作:文件读写
在Java中,IO流(Input/Output Streams)主要用于处理各种数据类型,包括字符、字节等。对于文件读写,主要通过以下几种IO流来实现:
- FileInputStream:
用于从文件中读取字节。
File file = new File("path_to_your_file");
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[1024]; // Read buffer
int bytesRead;
while ((bytesRead = fis.read(bytes))) != -1) {
// Process the read bytes
}
fis.close();
- FileOutputStream:
用于将字节写入到文件中。
// ... (From FileInputStream)
FileOutputStream fos = new FileOutputStream(file);
byte[] bytesToWrite = ... // Your bytes to write
fos.write(bytesToWrite); // Write the bytes
fos.flush(); // Ensure writes are flushed to the disk
fos.close();
- BufferedReader/ BufferedWriter:
用于从文件中读取字符,以及将字符写入到文件中。
// ... (From FileInputStream)
File file = new File("path_to_your_file");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))));
String line;
while ((line = br.readLine())) != null) {
// Process the read line
}
br.close();
// ... (For writing characters to file)
以上就是Java中文件读写的基本操作,实际使用时还需要根据具体需求进行调整。
还没有评论,来说两句吧...