如何通过用户定义的路径创建文本文件

时间:2016-03-09 23:20:07

标签: javascript java string file text-files

我正在尝试创建一个文本(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:");

2 个答案:

答案 0 :(得分:1)

假设您已成功将文件读入字符串并将数字读入数字数组,并且路径是绝对路径。

String nameOfTheFile = "/absolute/path";
int[] numbersToStore = new int[]{1,2,3,4,5};

然后您将在以下位置创建.txt文件:

File txtWithNumbers = new File(nameOfTheFile + ".txt");
BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(
         new FileOutputStream(txtWithNumbers), charSet
    )
); 
try {
    for(int i in numbersToStore) {
        writer.write(i + "\n");
    }
} finally {
    writer.close();
}

答案 1 :(得分:1)

首先创建一个java.io.FileWriter对象,然后根据该FileWriter对象创建一个java.io.PrintWriter。然后,您可以使用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块中以处理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