how to delete the content of text file without deleting itself

前端 未结 17 1173
逝去的感伤
逝去的感伤 2020-11-28 03:05

I want to copy the content of file \'A\' to file \'B\'. after the copying is done I want to clear the content of file \'A\' and want to write on it from its beginning. I can

相关标签:
17条回答
  • 2020-11-28 03:45

    Just print an empty string into the file:

    PrintWriter writer = new PrintWriter(file);
    writer.print("");
    writer.close();
    
    0 讨论(0)
  • 2020-11-28 03:45

    With try-with-resources writer will be automatically closed:

    import org.apache.commons.lang3.StringUtils;
    final File file = new File("SomeFile");
    try (PrintWriter writer = new PrintWriter(file))  {
        writer.print(StringUtils.EMPTY);                
    }
    // here we can be sure that writer will be closed automatically
    
    0 讨论(0)
  • 2020-11-28 03:47

    using : New Java 7 NIO library, try

            if(!Files.exists(filePath.getParent())) {
                Files.createDirectory(filePath.getParent());
            }
            if(!Files.exists(filePath)) {
                Files.createFile(filePath);
            }
            // Empty the file content
            writer = Files.newBufferedWriter(filePath);
            writer.write("");
            writer.flush();
    

    The above code checks if Directoty exist if not creates the directory, checks if file exists is yes it writes empty string and flushes the buffer, in the end yo get the writer pointing to empty file

    0 讨论(0)
  • 2020-11-28 03:51

    One liner to make truncate operation:

    FileChannel.open(Paths.get("/home/user/file/to/truncate"), StandardOpenOption.WRITE).truncate(0).close();
    

    More information available at Java Documentation: https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html

    0 讨论(0)
  • 2020-11-28 03:53

    You want the setLength() method in the class RandomAccessFile.

    0 讨论(0)
  • 2020-11-28 03:53

    After copying from A to B open file A again to write mode and then write empty string in it

    0 讨论(0)
提交回复
热议问题