Java中IO流的使用,如文件读写实例

原创 约定不等于承诺〃 2024-10-19 14:33 101阅读 0赞

在Java中,I/O(Input/Output)流主要用于处理输入和输出数据。以下是一些常见的IO流以及它们的使用实例:

  1. FileInputStream:用于从文件中读取数据。

    1. try {
    2. FileInputStream fis = new FileInputStream("example.txt");
    3. byte[] bytes = new byte[1024]; // 一次性读取1KB
    4. int read = fis.read(bytes);
    5. while (read != -1) { // 如果不为空,继续读取
    6. System.out.print(new String(bytes, 0, read))));
    7. read = fis.read(bytes); // 重新读取数据
    8. }
    9. fis.close(); // 关闭文件输入流
    10. } catch (FileNotFoundException e) {
    11. e.printStackTrace();
    12. }
  2. FileOutputStream:用于将数据写入文件。

    1. try {
    2. FileOutputStream fos = new FileOutputStream("example.txt");
    3. String content = "Hello, World!"; // 要写入的字符串
    4. fos.write(content.getBytes()); // 将字符串转换为字节数组,然后写入
    5. fos.close(); // 关闭文件输出流
    6. } catch (FileNotFoundException e) {
    7. e.printStackTrace();
    8. }
  3. BufferedReader:用于从字符输入流中读取数据。

    1. try {
    2. BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("example.txt")))));
    3. String line;
    4. while ((line = br.readLine()) != null) { // 逐行读取
    5. System.out.println(line);
    6. }
    7. br.close(); // 关闭缓冲读流
    8. } catch (IOException e) {
    9. e.printStackTrace();
    10. }

这些实例展示了Java中IO流的基本使用。在实际项目中,根据需求可能会进行更复杂的操作。

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

发表评论

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

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

相关阅读