how to delete the content of text file without deleting itself

前端 未结 17 1178
逝去的感伤
逝去的感伤 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:54

    Simple, write nothing!

    FileOutputStream writer = new FileOutputStream("file.txt");
    writer.write(("").getBytes());
    writer.close();
    
    0 讨论(0)
  • 2020-11-28 04:02
    FileOutputStream fos = openFileOutput("/*file name like --> one.txt*/", MODE_PRIVATE);
    FileWriter fw = new FileWriter(fos.getFD());
    fw.write("");
    
    0 讨论(0)
  • 2020-11-28 04:02

    you can write a generic method as (its too late but below code will help you/others)

    public static FileInputStream getFile(File fileImport) throws IOException {
          FileInputStream fileStream = null;
        try {
            PrintWriter writer = new PrintWriter(fileImport);
            writer.print(StringUtils.EMPTY);
            fileStream = new FileInputStream(fileImport);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                writer.close();
            }
             return fileStream;
    }
    
    0 讨论(0)
  • 2020-11-28 04:04

    I don't believe you even have to write an empty string to the file.

    PrintWriter pw = new PrintWriter("filepath.txt");
    pw.close();
    
    0 讨论(0)
  • 2020-11-28 04:09

    Just write:

    FileOutputStream writer = new FileOutputStream("file.txt");
    
    0 讨论(0)
  • 2020-11-28 04:09

    If you don't need to use the writer afterwards the shortest and cleanest way to do it would be like that:

    new FileWriter("/path/to/your/file.txt").close();
    
    0 讨论(0)
提交回复
热议问题