java中如何使用io流读写文件

分类:网络文章 时间:2024-01-24 12:03 浏览:0 评论:0
0

Java中使用IO流读写文件主要涉及到以下几个类和接口:

  1. FileInputStream和FileOutputStream:用于读写字节流的文件,以字节为单位进行读写。
  2. FileReader和FileWriter:用于读写字符流的文件,以字符为单位进行读写。
  3. BufferedReader和BufferedWriter:用于提供缓冲机制,能够提高读写效率。
  4. InputStreamReader和OutputStreamWriter:用于将字节流转换为字符流,以便进行字符流的读写操作。

下面是一些常用的读写文件的示例代码:

  1. 使用FileInputStream和FileOutputStream读写字节流的文件:
import java.io.*;public class FileIOExample {    public static void main(String[] args) {        try {            FileInputStream fis = new FileInputStream("input.txt");            FileOutputStream fos = new FileOutputStream("output.txt");            int data;            while ((data = fis.read()) != -1) {                fos.write(data);            }            fis.close();            fos.close();        } catch (IOException e) {            e.printStackTrace();        }    }}
  1. 使用FileReader和FileWriter读写字符流的文件:
import java.io.*;public class FileIOExample {    public static void main(String[] args) {        try {            FileReader fr = new FileReader("input.txt");            FileWriter fw = new FileWriter("output.txt");            int data;            while ((data = fr.read()) != -1) {                fw.write(data);            }            fr.close();            fw.close();        } catch (IOException e) {            e.printStackTrace();        }    }}
  1. 使用BufferedReader和BufferedWriter读写文件:
import java.io.*;public class FileIOExample {    public static void main(String[] args) {        try {            BufferedReader br = new BufferedReader(new FileReader("input.txt"));            BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));            String line;            while ((line = br.readLine()) != null) {                bw.write(line);                bw.newLine(); // 写入换行符            }            br.close();            bw.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

这些示例代码只是基本的读写文件操作,具体使用时可能还需要处理异常、关闭流等。

1. 本站所有资源来源于用户上传或网络,仅作为参考研究使用,如有侵权请邮件联系站长!
2. 本站积分货币获取途径以及用途的解读,想在本站混的好,请务必认真阅读!
3. 本站强烈打击盗版/破解等有损他人权益和违法作为,请各位会员支持正版!
4. 网络文章 > java中如何使用io流读写文件

用户评论