我正在尝试创建一个文本(numbers.txt)文件,用户在其中指示他们可以保存文件。我知道
File directory = new File("/home/jon/somewhere");
File fullPath = new File(directory, fileName);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
(new FileOutputStream(fullPath), charSet));
try {
writer.write("\n");
writer.write("work");
} finally {
writer.close();
}
需要插入,但我不知道如何让它在该位置创建 .txt 文件,该位置是用户通过扫描仪定义的。这是到目前为止我的代码,直到我期望输入上面的代码为止。使用 Eclipse IDE,如果需要此信息。
代码的要点是将数字保存到txt文件中,然后拉回来读取它们,以便可以计算它们。
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.Scanner;
import java.io.Serializable;
import java.lang.SecurityException;
import java.util.Formatter;
public class StrangeAverage implements Serializable{
/**
* @param args
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int fails = 0;
do {
System.out.printf("Please enter a directory where you can save files, in case of error/shutdown: ");
Path path = Paths.get(input.nextLine());
if (Files.isDirectory(path))
{
System.out.println("Using Directory " +path);
break;
}
else
{
System.out.println("That's not an open directory.");
fails++;
}
}while(fails < 5);
if (fails == 5)
{
System.out.print("Too many failed attempts. Exiting...");
return;
}
if (fails < 5)
{
System.out.println("Valid Directory.");
}
System.out.printf("Please enter ten integers:");
最佳答案
创建 java.io.FileWriter
首先对象,然后创建一个 java.io.PrintWriter
基于该 FileWriter
对象。然后您可以使用 PrintWriter.print()
将文本添加到文件中:
FileWriter fileWriter = new FileWriter("filename.ext", true);
PrintWriter out = new PrintWriter(fileWriter);
out.print("Text to go in the file");
out.println("Text to go in the file");
请注意,您需要将此代码包含在 try-catch
block 中以处理 IOExceptions
:
try {
FileWriter fileWriter = new FileWriter("filename.ext", true);
PrintWriter out = new PrintWriter(fileWriter);
out.print("Text to go in the file");
out.println("Text to go in the file");
} catch (java.io.IOException e) {
//handle
}
out.close(); //Don't forget to close the file when done
关于javascript - 如何通过用户定义的路径创建文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35904641/