我写了一个简短的脚本来创建一个文件到我的桌面,文件出现了 . 我只是在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机器上,我想再次将它发送到我的桌面,所以我的用户输入是userPath的“/ home / christopher / Desktop” . 没啥事儿 . 我甚至通过终 endpoints 击我的桌面到那里的“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");
我的调试尝试的print语句输出“/ home / christopher / Desktop”,但不是输出到目录的文件名 .
感谢您提供的任何帮助 . 这仅用于学习Java I / O的实验 . 由于假设用户可能与我在同一个操作系统上,我可以稍后处理这些方法 . 我将它保存在我的家用机器上,因此是Unix文件路径名称 .
1 回答
将input.nextLine()更改为input.next()解决了问题 . 在询问用户是否确定其输入的路径是所需的保存点后,程序未到达if语句 .
我还输入了一个简单的else语句,打印出来(“File not created”)以验证它是否正在跳过它 .
无论如何,问题回答了 . :-)