我想将文件“ A”的内容复制到文件“ B”。复制完成后,我想清除文件“ A”的内容,并希望从文件开始就开始写。我无法删除文件“ A”,因为它与其他一些任务有关。
我能够使用Java的文件API(readLine())复制内容,但不知道如何清除文件内容并将文件指针设置为文件的开头。
Answers:
我认为您甚至不必在文件中写入一个空字符串。
PrintWriter pw = new PrintWriter("filepath.txt");
pw.close();
new PrintWriter("filepath.txt").close();?
您需要在RandomAccessFile类中使用setLength()方法。
简单,什么都不写!
FileOutputStream writer = new FileOutputStream("file.txt");
writer.write(("").getBytes());
writer.close();
进行截断操作的一根衬垫:
FileChannel.open(Paths.get("/home/user/file/to/truncate"), StandardOpenOption.WRITE).truncate(0).close();
Java文档上提供了更多信息:https : //docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html
下面如何:
File temp = new File("<your file name>");
if (temp.exists()) {
RandomAccessFile raf = new RandomAccessFile(temp, "rw");
raf.setLength(0);
}
Java最佳伴侣之一是Apache Projects,请务必参考它。对于与文件相关的操作,您可以参考Commons IO项目。
下面的一行代码将帮助我们将文件清空。
FileUtils.write(new File("/your/file/path"), "")
使用:新的Java 7 NIO库,尝试
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();
上面的代码检查Directoty是否存在(如果未创建目录),检查文件是否存在,则写入空字符串并刷新缓冲区,最后使写入器指向空文件
您可以使用
FileWriter fw = new FileWriter(/*your file path*/);
PrintWriter pw = new PrintWriter(fw);
pw.write("");
pw.flush();
pw.close();
记住不要使用
FileWriter fw = new FileWriter(/*your file path*/,true);
在filewriter构造函数中为true将启用append。
FileOutputStream fos = openFileOutput("/*file name like --> one.txt*/", MODE_PRIVATE);
FileWriter fw = new FileWriter(fos.getFD());
fw.write("");
您要做的就是在截断模式下打开文件。任何Java文件输出类都会自动为您完成此操作。
您可以编写一个通用方法,因为(为时已晚,但是下面的代码将对您/其他人有所帮助)
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;
}