java 字符串 转 文件路径_连接用户输入字符串转换为完整的文件路径(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机器上,我想再次将它发送到我的桌面,所以我的用户输入是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文件路径名称 .

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值