连接用户输入的字符串以转换为完整的文件路径 (Java)

Concatenate user input Strings to convert into a complete file path (Java)

我写了一个简短的脚本来创建一个文件到我的桌面,然后文件出现了。我只是在 main 中完成了所有操作,如下所示:

    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 机器上,我想再次将它发送到我的桌面,所以我的用户输入是用户路径的“/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。由于假设的用户可能与我不在同一个 OS 上,我可以稍后处理这些方法。我将它保存在我的家用机器上,因此是 Unix 文件路径名称。

将 input.nextLine() 更改为 input.next() 解决了问题。在询问用户是否确定他们输入的路径是所需的保存点后,程序没有到达 if 语句。

我还放入了一个打印出来的简单 else 语句 ("File not created") 以验证它是否正在跳过它。

总之,问题已回答。 :-)