Java中的文件操作,如读写、删除等

原创 小灰灰 2024-09-17 15:42 153阅读 0赞

在Java中,我们可以使用内置的java.io包进行文件操作。以下是一些基本的操作:

  1. 创建文件 - FileWriterPrintWriter

    1. File file = new File("path/to/your/file.txt");
    2. try (FileWriter writer = new FileWriter(file)) {
    3. // write to the file
    4. } catch (IOException e) {
    5. e.printStackTrace();
    6. }
  2. 读取文件 - BufferedReader or FileReader

    1. File file = new File("path/to/your/file.txt");
    2. try (BufferedReader reader = new BufferedReader(new FileReader(file)))) {
    3. // read from the file
    4. String line;
    5. while ((line = reader.readLine()) != null) {
    6. System.out.println(line);
    7. }
    8. } catch (IOException e) {
    9. e.printStackTrace();
    10. }
  3. 写入追加模式 - FileWriter

    1. File file = new File("path/to/your/file.txt");
    2. try (FileWriter writer = new FileWriter(file, true)) {
    3. // write to the file in append mode
    4. } catch (IOException e) {
    5. e.printStackTrace();
    6. }
  4. 删除文件 - File

    1. File file = new File("path/to/your/file.txt");
    2. if (file.delete()) {
    3. System.out.println("File deleted successfully.");
    4. } else {
    5. System.out.println("Failed to delete the file.");
    6. }

以上就是Java中进行基本文件操作的一些示例。

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

发表评论

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

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

相关阅读