Java中的IO流操作:文件读写

原创 清疚 2024-10-06 09:39 170阅读 0赞

在Java中,IO流(Input/Output Streams)主要用于处理各种数据类型,包括字符、字节等。对于文件读写,主要通过以下几种IO流来实现:

  1. FileInputStream
    用于从文件中读取字节。
  1. File file = new File("path_to_your_file");
  2. FileInputStream fis = new FileInputStream(file);
  3. byte[] bytes = new byte[1024]; // Read buffer
  4. int bytesRead;
  5. while ((bytesRead = fis.read(bytes))) != -1) {
  6. // Process the read bytes
  7. }
  8. fis.close();
  1. FileOutputStream
    用于将字节写入到文件中。
  1. // ... (From FileInputStream)
  2. FileOutputStream fos = new FileOutputStream(file);
  3. byte[] bytesToWrite = ... // Your bytes to write
  4. fos.write(bytesToWrite); // Write the bytes
  5. fos.flush(); // Ensure writes are flushed to the disk
  6. fos.close();
  1. BufferedReader/ BufferedWriter
    用于从文件中读取字符,以及将字符写入到文件中。
  1. // ... (From FileInputStream)
  2. File file = new File("path_to_your_file");
  3. BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))));
  4. String line;
  5. while ((line = br.readLine())) != null) {
  6. // Process the read line
  7. }
  8. br.close();
  9. // ... (For writing characters to file)

以上就是Java中文件读写的基本操作,实际使用时还需要根据具体需求进行调整。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,170人围观)

还没有评论,来说两句吧...

相关阅读