解决Mac和Windows之间的路径差异
问题描述:
我是Stack Overflow的新手,对于编程来说相当新颖,所以希望这很有道理。我正在写一个Java程序,在特定的目录中创建一个文件。我的程序在Windows上工作,并在正确的位置创建一个文件,但它不适用于Mac。我试图将反斜杠改为单个正斜杠,但这不起作用。我应该如何更改代码以使其适用于Mac或理想情况下适用于两者?我已经把下面的一些代码。解决Mac和Windows之间的路径差异
在此先感谢!
try{
//Create file path
String dirpath = new ReWriterRunner().getPath()+"NewFiles";
//Create directory if it doesn't exist
File path = new File(dirpath);
if (!path.exists()) {
path.mkdir();
}
//Create file if it doesn't exist
File readme = new File(dirpath+"\\README.md");
if (!readme.exists()) {
readme.createNewFile();
}
方法沾到往哪里放文件的用户输入:对于文件创建新的路径
类
public static String getPath(){
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter the directory name under which the project files are stored.");
System.out.println("Example: C:\\Users\\user\\work\\jhipstertesting)");
System.out.println("Use double slashes when typing.");
s = in.nextLine();
return s;
}
答
您可以使用系统属性来确定在https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
您正在上运行.. 更多信息的系统,但我宁愿使用NIO。但这是你的选择
https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
答
正斜杠“/”必须被用来获取文件路径这里。为前>用途:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
使用系统属性工作完美。感谢您的帮助! – avl7949