在Java中我想创建一个文件并在其上保存数据。带有路径的File
名称取自用户。现在,如果用户给出无效路径,如C:\temp\./user\fir/st.csv
这是一条无效路径,因为"."
和/
在路径中,而在Windows操作系统"\"
被用作路径分隔符。如何知道在java中保存文件的无效路径
执行程序(一命令行工具)之前,没有temp
文件夹中C:\
目录,但是当我运行该程序会创建temp
文件夹,然后在temp
它创建user
然后在user
它创建fir
文件夹终于在st.csv
里面。虽然我希望如果用户用户给出这种类型的无效路径或文件名应通过消息"Invalid path or file name"
注意。
我该怎么办?程序代码如下图所示:
public class FileTest {
public static void main(String args[]) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter path:");
String path = br.readLine();
File file = new File(path);
String path1 = file.getParent();
File file2 = new File(path1);
if (!file2.exists()) {
System.out.println("Directory does not exist , So creating directory");
file2.mkdirs();
}
if (!file2.exists()) {
System.out.println("Directory can not be created");
} else {
FileWriter writer = new FileWriter(file);
PrintWriter out = new PrintWriter(writer);
System.out.println("Please enter text to write on the file, print exit at new line to if finished");
String line = "";
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("exit")) {
System.out.println("Thanks for using our system");
System.exit(0);
} else {
out.println(line);
out.flush();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
现在,如果我给作为C:\tump\./user\fir/st.csv
那么它在C
驱动器tump
创建tump
文件夹,然后用户,然后在fir
夹user
然后st.csv
文件在它的路径。
请不要仅从您的其他站点复制并粘贴您的问题。至少要为StackOverflow正确设置格式。 –
这是我自己在我的项目中遇到的问题,代码如上,但实际的代码非常大,这是一个命令行工具,现在我执行缩进 –