连接用户输入字符串以转换为完整的文件路径(Java)
我写了一个简短的脚本,在我的桌面上创建了一个文件,文件出现了。我基本上都是这样做的:
import java.io.*;
import java.util.Scanner;
public class FilePractice {
public static void main(String[] args) {
//create a new File object
File myFile = new File("/home/christopher/Desktop/myFile");
try{
System.out.println("Would you like to create a new file? Y or N: ");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
myFile.createNewFile();
}
else
{
//do nothing
}
}catch(IOException e) {
System.out.println("Error while creating file " + e);
}
System.out.println("'myFile' " + myFile.getPath() + " created.");
}
}
我只是想确保代码正常工作,它确实做到了。在那之后,我想通过创建一个包含用户输入的文件进行扩展,并定义用户希望将文件发送到哪个目录。我在一台Linux机器上,我想再次将它发送到我的桌面,所以我的用户输入是userPath的“/home/christopher/Desktop”。什么也没发生。我甚至通过终端将cd刻录到我的桌面,以“ls”那里的所有内容,但仍然一无所获
也许我的语法错了
如果这是复制品,我道歉。在来到这里之前,我试图进行彻底的搜索,但我只找到了有关创建文件和将文件发送到已定义为字符串的目录的信息(例如File myFile=new File(“/home/User/Desktop/myFileName”))
以下是扩展的尝试:
try {
System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
String fileName = input.nextLine();
input.nextLine();
System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
String userFilePath = input.nextLine();
File userFile = new File(userFilePath, fileName);
System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
String userChoice = input.nextLine();
if (userChoice.equalsIgnoreCase("Y")) {
userFile.createNewFile();
//print for debug
System.out.println(userFile.getPath());
}
}catch(IOException e) {
System.out.println("Error while attempting to create file " + e);
}
System.out.println("File created successfully");
调试尝试的打印语句输出“/home/christopher/Desktop”,但不输出附加到目录的文件名
谢谢你的帮助。这只是为了在学习Java I/O时进行实验。由于假设的用户可能与我不在同一操作系统上,我可以在以后研究这些方法。我将它保存在我的家庭计算机上,因此使用Unix文件路径名
# 1 楼答案
改变输入。nextLine()来输入。next()解决了这个问题。在询问用户是否确定输入的路径是所需的保存点后,程序没有到达if语句
我还输入了一个简单的else语句,打印出来(“文件未创建”),以验证它是否跳过了它
不管怎样,问题得到了回答。:-)