我写了一个简短的脚本来创建一个文件到我的桌面,并出现文件。我只是做了所有主要的,像这样:Concantenate用户输入字符串转换成完整的文件路径(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 /克里/桌面” print语句,但不追加到目录中的文件名。
感谢您提供的任何帮助。这只是在学习Java I/O时进行实验。由于假想的用户可能与我不在同一个操作系统上,因此我可以在以后处理这些方法。我将它保存在我的主机上,因此是Unix文件路径的名称。