how to delete the content of text file without deleting itself

前端 未结 17 1177
逝去的感伤
逝去的感伤 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 04:09

    You can use

    FileWriter fw = new FileWriter(/*your file path*/);
    PrintWriter pw = new PrintWriter(fw);
    pw.write("");
    pw.flush(); 
    pw.close();
    

    Remember not to use

    FileWriter fw = new FileWriter(/*your file path*/,true);
    

    True in the filewriter constructor will enable append.

    0 讨论(0)
  • 2020-11-28 04:09

    All you have to do is open file in truncate mode. Any Java file out class will automatically do that for you.

    0 讨论(0)
  • 2020-11-28 04:10

    Write an empty string to the file, flush, and close. Make sure that the file writer is not in append-mode. I think that should do the trick.

    0 讨论(0)
  • 2020-11-28 04:11

    One of the best companion for java is Apache Projects and please do refer to it. For file related operation you can refer to the Commons IO project.

    The Below one line code will help us to make the file empty.

    FileUtils.write(new File("/your/file/path"), "")
    
    0 讨论(0)
  • 2020-11-28 04:12

    How about below:

    File temp = new File("<your file name>");
    if (temp.exists()) {
        RandomAccessFile raf = new RandomAccessFile(temp, "rw");
        raf.setLength(0);
    }
    
    0 讨论(0)
提交回复
热议问题