我有一个像这样的Path变量:
Path output;
该路径在main方法中初始化。
我想检查这个路径中是否存在一个文件如果是这种情况,在文件中写入一个字符串。否则,创建一个具有给定路径的新文件并写入字符串。
//void parseOutput(String s){
//if (file in path exists)
// write(s in file from path)
else
File f = new File(String.valueOf(output));
write String in f
You can try this :
import java.io.*;
class FileDemo {
public static void main(String str[]) {
String path = "E:/myfile.txt";
File file = new File(path);
if(file.exists()) {
System.out.println("File is exist..!!!");
} else {
try {
FileWriter fileWriter = new FileWriter(path);
fileWriter.write("This is my first file..!!");
fileWriter.close();
System.out.println("File has some content..!!");
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}
}
}
如果您有一个Path,那么将其转换为String并使用File构造函数是没有意义的。
检查文件是否存在,可以使用Files exists.
要添加到现有文件中,请查看文件。使用APPEND OpenOption设置newBufferedWriter
完整的示例:
Path path = Paths.get("/path/to/file.txt");
try (BufferedWriter bufferedWriter = Files.newBufferedWriter(
path, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
PrintWriter printWriter = new PrintWriter(bufferedWriter))
{
printWriter.println("This is a line");
}
您可能希望在File类中使用exists()方法。下面是一个你可以使用的例子:
public void writeOnFile(String path, String str) throws FileNotFoundException {
PrintWriter out;
File file = new File(path);
if (file.exists()){
out = new PrintWriter(file.getPath());
out.println(str);
}
}