我正在尝试制作一个允许创建“ txt”文件的小程序。我的老师教我使用BufferedReader和PrintWriter,但我不知道如何让用户选择路径(您知道,例如在软件上保存内容时)。
感谢您的回答。 (抱歉,我的英语不是我的母语)
答案 0 :(得分:0)
您可以使用Scanner
输入文件,然后使用Path#get
将文件名附加到文件名:
System.out.println("Please enter the target directory: ");
Scanner in = new Scanner(System.in);
String dir = in.next();
String filePath = Paths.get(dir, "myfile.txt").toString();
// Go on and create the file as you would normally do
答案 1 :(得分:0)
我假设您要使用BufferedReader,它是控制台应用程序。
public class CreateFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in));) {
System.out.println("Enter the path");
String path = br.readLine();
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created!");
}
}
}
输出
输入路径
./ file / test.txt
文件已创建!
带有界面,是获取用户输入的最简单方法
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JOptionPane;
public class CreateFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String path = JOptionPane.showInputDialog("Enter the path");
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created!");
}
}
}