我有一些输入费用的代码。但是,程序不会将文本文件写入Linux上的指定文件夹(Ubuntu 16.04)。该程序用于正常写入代码所在文件夹中的文件。现在,我正在尝试将文件写入特定文件夹,但它失败了(即使我为所有用户设置了读取,写入和执行权限,也没有创建该文件。)我想添加该代码制作目录但无法在特定目录中写入文件。任何帮助或指导将不胜感激。
import java.io.*
import java.util.EnumSet;
import java.util.Set;
public class Create_File {
private Services services = new Services();
final Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx");
public void create_File(String content) {
int product_id =0;
String headline = "XXXX" ;
String username = System.getProperty("user.home");
String dataFolder = System.getProperty("user.home") + "/My_Data/Budget_backup";
System.out.println(username);
File directory = new File(dataFolder+File.separator+"Budget_app_data_expenses");
String name_of_file = "budget_back_up.txt";
File file = new File(directory+File.separator+ name_of_file);
System.out.println(file.toString());
Path path = FileSystems.getDefault().getPath(dataFolder, name_of_file );
if (Files.notExists(path, new LinkOption[]{LinkOption.NOFOLLOW_LINKS})){
try {
Files.createDirectories(
Paths.get(dataFolder),
PosixFilePermissions.asFileAttribute(perms));
//directory.mkdirs();
//file.createNewFile();
product_id = 1;
System.out.println("file created");
FileWriter writer = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(writer);
bw.write(headline);
bw.close();
}catch(IOException ex){
ex.printStackTrace();
}
}else {
product_id = services.max_id();
System.out.println("The directory is already on the computer");
try {
FileWriter writer = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("\n"+ "("+ product_id + " , " +content);
bw.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
答案 0 :(得分:2)
此错误可能是由于给定路径中没有目录。需要创建,可以使用mkdirs()
创建/home/USER/My_Data/Budget_backup/Budget_app_data_expenses/budget_back_up.txt (No such file or directory)
最初创建目录后,您不应该遇到任何错误
取消注释directory.mkdirs()在Mac和Fedora中都适用于我
Files.createDirectories(
Paths.get(dataFolder),
PosixFilePermissions.asFileAttribute(perms));
directory.mkdirs();
另请查看您的代码
String dataFolder = System.getProperty("user.home") + "/My_Data/Budget_backup";
File directory = new File(dataFolder+File.separator+"Budget_app_data_expenses");
File file = new File(directory+File.separator+ name_of_file);
Path path = FileSystems.getDefault().getPath(dataFolder, name_of_file );
在路径对象中,您尝试在错误的目录中找到该文件/ My_Data / Budget_backup&#34;
在/ My_Data / Budget_backup / Budget_app_data_expenses中创建文件
在这种情况下,你的if条件在错误的目录中搜索文件,而if条件总是为true,因为你的路径不正确