java文件读取和写入的方法是什么

30次阅读
没有评论

共计 1350 个字符,预计需要花费 4 分钟才能阅读完成。

Java 中读取和写入文件的方法有很多,以下是其中几种常用的方法:

  1. 使用 File 类:可以使用 File 类来创建、删除、重命名文件,以及检查文件是否存在等操作。可以通过 FileInputStream 和 FileOutputStream 来读取和写入文件内容。

示例代码:

// 读取文件 
File file = new File("path/to/file.txt");
try (FileInputStream fis = new FileInputStream(file)) {int content;
    while ((content = fis.read()) != -1) {System.out.print((char) content);
    }
} catch (IOException e) {e.printStackTrace();
}

// 写入文件 
try (FileOutputStream fos = new FileOutputStream(file)) {String content = "Hello, World!";
    fos.write(content.getBytes());
} catch (IOException e) {e.printStackTrace();
}
  1. 使用 BufferedReader 和 BufferedWriter 类:这两个类提供了带缓冲区的读取和写入文件内容的方法,可以提高读写效率。

示例代码:

// 读取文件 
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {System.out.println(line);
    }
} catch (IOException e) {e.printStackTrace();
}

// 写入文件 
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {String content = "Hello, World!";
    bw.write(content);
} catch (IOException e) {e.printStackTrace();
}
  1. 使用 Scanner 类:Scanner 类可以用来读取文件中的各种类型的数据,如整数、浮点数、字符串等。

示例代码:

// 读取文件 
try (Scanner scanner = new Scanner(file)) {while (scanner.hasNextLine()) {String line = scanner.nextLine();
        System.out.println(line);
    }
} catch (FileNotFoundException e) {e.printStackTrace();
}

// 写入文件 
try (PrintWriter writer = new PrintWriter(file)) {String content = "Hello, World!";
    writer.println(content);
} catch (FileNotFoundException e) {e.printStackTrace();
}

以上是几种常用的文件读取和写入的方法,根据具体的需求选择合适的方法来操作文件。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计1350字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)