我的程序只是读取2个值,然后对它们进行一些操作。(这部分并不重要。)首先,我必须检查文件名。例如我的程序以
输入文件名:
输入文件名时,程序应检查项目工作区中是否存在具有该名称的文件。我在项目库中有一个文件,我想检查:“此文件名与用户给定名称是否相同”。
String workingDir = System.getProperty("user.dir");
我可以使用此代码获取工作区位置。
File a = new File(" --Workspace direction-- ");
if(filename.equals(a.getName())){
}
我创建了一个新文件,并尝试与.getName()
方法进行比较。问题是我认为工作区中缺少.txt文件名。当我得到第一个代码的工作位置时,我只有
/用户/ asd /文档/工作区/项目/
这。但是,为了能够获取文件名,该文件路径的末尾应该有文件名。如何检查工作区目录中是否存在用户输入指定名称的文件?
假设inputName
包含用户输入:
/* In your case, this is entered by the user */
String inputName = "testfile.txt";
然后,您将获得工作空间目录:
String workingDir = System.getProperty("user.dir");
现在,您想知道该工作空间目录中是否存在名为“ testfile.txt”的文件。为此类文件创建一个File实例:
// a File instance for the directory:
File workingDirFile = new File(workingDir);
// a File instance for a file in that directory:
File testfile = new File(workingDirFile, inputName);
现在,您应该具有workingDirFile
包含“ / Users / asd / Documents / workspace / project /”和testfile
包含“ /Users/asd/Documents/workspace/project/testfile.txt”的文件。要检查文件是否存在:
if (testfile.exists()) {
/* file with name "testfile.txt" exists in project dir */
} else {
/* file with name "testfile.txt" does not exist in project dir */
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句