简体   繁体   English

创建文件Java时遇到问题

[英]Trouble in creating file java

currently I'm working on a project and I have to change the savepath of my application. 目前,我正在开发一个项目,必须更改应用程序的保存路径。 So I will firstly check if the directory exists using 因此,我将首先使用以下命令检查目录是否存在

File file = new File(path);
file.exists();

My problem is that the method file.exists() returns false even when I try to input C: as my path. 我的问题是,即使我尝试输入C:作为路径,方法file.exists()也会返回false。 Nevertheless, if I don't specify any folder, let say : 不过,如果我未指定任何文件夹,请说:

File file = new File("testFile.xml");

Then the new file will be created in the main directory. 然后,新文件将在主目录中创建。 I suspect Eclipse automatically adds a relative path everytime I do the check since when I use text editor, the following returns true 我怀疑Eclipse每次执行检查时都会自动添加一个相对路径,因为当我使用文本编辑器时,以下返回true

new File("C:").exists()

Now, is there any way to tell Eclipse to recognise the path that I enter as an absolute path? 现在,有什么方法可以告诉Eclipse将我输入的路径识别为绝对路径吗?

Thanks! 谢谢!

EDITED **** 编辑****

I found that my problem is that Eclipse seems to auto append every file path that I create with the source directory 我发现我的问题是Eclipse似乎会自动附加我用源目录创建的每个文件路径

File = new File("C:/")

will give me 会给我

"C:\Users\Christopher\Documents\School Stuff\CS2103\JOBS\main\C:\"

which is automatically appended by eclipse with the project directory and hence, disabling me from creating file outside of my project directory eclipse会自动将其附加到项目目录,因此使我无法在项目目录之外创建文件

您可以尝试file.getAbsoluteFile().exists()吗?

File.isAbsolute() : File.isAbsolute()

File file = new File(path);
if (file.isAbsolute()) {

}

in Eclipse, right click on project and go to run> run configuration and go to arguments give the default path for saving file.... project always create file on that location. 在Eclipse中,右键单击项目,然后转到“运行”>“运行配置”,然后转到参数以提供用于保存文件的默认路径。...项目始终在该位置创建文件。

            File fileTest = new File("C:/test");
            if (!fileTest.exists()) {
                if (fileTest.mkdirs()) {
                    fileTest.setReadable(true, false);
                    fileTest.setWritable(true, false);
                } else {
                System.out.println("Failed To Create Directories! :-"+ "C:/");
                }
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM