【发布时间】:2011-10-11 12:27:03
【问题描述】:
在 Java 中,我想从中创建一个文件并将数据保存在上面。带有路径的File 名称取自用户。现在,如果用户给出无效路径,例如 C:\temp\./user\fir/st.csv,这是一个无效路径,因为 "." 和 / 在路径中,并且在 Windows 操作系统上,"\" 用作路径分隔符。
在执行程序之前(一个命令行工具),C:\ 目录中没有temp 文件夹,但是当我运行程序时它会创建temp 文件夹然后在@987654329 @ 它创建 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 中创建用户,然后在 user 文件夹中创建 fir,然后在其中创建 st.csv 文件。
【问题讨论】:
-
请不要只是从其他网站复制和粘贴您的问题。至少要努力为 StackOverflow 正确格式化。
-
这是我自己在项目中遇到的问题,代码如上,但实际代码很大,是一个命令行工具,现在我已经执行了缩进
标签: java file filesystems