Java 保存当前目录下的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26251039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving files in current directory
提问by codename_newbie
I've been searching for this and many answers came out but it just wasn't the solution I was looking for so I came here and try to ask help to you guys...
我一直在寻找这个,很多答案出来了,但这不是我正在寻找的解决方案,所以我来到这里并试图向你们寻求帮助......
I want to create a .txt
file in the same folder where the JAR file is located (dist folder)...
我想.txt
在 JAR 文件所在的同一文件夹(dist 文件夹)中创建一个文件...
I tried using System.getProperty("user.dir")
it works fine when I run it on windows and using netbeans the file created is always in the same folder where the jar file is but when I run it on LINUX it saves the file in root... but the folder where the jar file is on the desktop
System.getProperty("user.dir")
当我在 Windows 上运行它并使用 netbeans 时,我尝试使用它工作正常,创建的文件始终位于 jar 文件所在的同一文件夹中,但是当我在 LINUX 上运行它时,它会将文件保存在根目录中... jar 文件在桌面上
it creates in the same folder when I use the terminal to open the jar file
当我使用终端打开 jar 文件时,它会在同一个文件夹中创建
private static String directory=System.getProperty("user.dir");
private final String sample=directory+File.separator+"sample.txt";
public void createFile()
{
File file=new File(sample);
try(FileWriter fw=new FileWriter(file))
{
fw.write("INSERT ME WHERE MY JAR IS");
fw.flush();
fw.close();
}catch(IOException ex)
{
ex.printStackTrace();
}
}
回答by travega
You can refer to your working directory with
你可以参考你的工作目录
File directory = new File(".")
and you can access a file on it using
你可以使用它访问一个文件
System.getProperty(directory.getCanonicalPath() + File.separator + "my.properties")
OR
或者
System.getProperty("." + File.separator + "my.properties")
The "." refers to your current directory. The use of File.separator
ensures your get '/' in UNIX-based file systems and "\" in NTFS.
这 ”。” 指的是您当前的目录。的使用File.separator
确保您在基于 UNIX 的文件系统中获得“/”和在 NTFS 中获得“\”。
回答by George Rosario
Had same problem: These will work for LINUX
有同样的问题:这些适用于LINUX
Current directory's canonical path:directory.getCanonicalPath());
当前目录的规范路径:directory.getCanonicalPath());
Current directory's absolute path:directory.getAbsolutePath());
当前目录的绝对路径:directory.getAbsolutePath());
If it varies in windows try to check for OS and run code: Like
如果它在 Windows 中有所不同,请尝试检查操作系统并运行代码:像
System.getProperty("os.name");
Or else Use:
否则使用:
String absolutePath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf("/"));