我正在创建一个目录,然后创建一个文件。问题是目录已创建,但文件不是。
当我这样做时,我正在创建并打印出“成功创建新文件:以及文件名称。
任何人都可以帮忙理解为什么吗?
public class Main
{
public static void main(String[] args) throws IOException
{
Scanner reader = new Scanner (System.in);
boolean success = false;
GetFiles getFile = new GetFiles();
System.out.println("Enter path of directory to create");
String dir = reader.nextLine();
// Create a new directory in Java, if it doesn't exists
File directory = new File(dir);
if(directory.exists())
{
System.out.println("Directory already exists");
}
else
{
System.out.println("Directory not exists, creating now");
success = directory.mkdir();
if(success)
System.out.println("Successfuly created new directory");
else
System.out.println("Failed to create new directory");
}
// Creatning new file in Java, only if not exists
System.out.println("Enter file name to be created");
String filename = reader.nextLine();
File f = new File(filename);
if(f.exists())
{
System.out.println("File already exists");
}
else
{
System.out.println("No such file exists, creating now");
success = f.createNewFile();
if(success)
System.out.printf("Successfully created new file: : %s%n", f);
else
System.out.printf("Failed to create new file: %s%n", f);
}
reader.close();
getFile.getAllFiles(directory);
}
}
答案 0 :(得分:2)
您的代码完全正常运行。它实际上创建了文件。您可以在java项目中看到创建的文件。
只需添加此行代码,它就可以正常工作。
filename = dir + "\\" + filename;
File f = new File(filename);