简体   繁体   English

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

[英]How to create text file through user-defined path

I'm attempting to create a text (numbers.txt) file where the user indicates that they can save files. 我正在尝试创建一个文本(numbers.txt)文件,其中用户指示他们可以保存文件。 I know 我知道

    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();
}

needs to be inserted, but I don't know how to make it create the .txt file at that location, which is user defined through the scanner. 需要插入,但是我不知道如何使它在该位置创建.txt文件,该文件是用户通过扫描仪定义的。 Here's my code so far, up to the point I'm expecting to input the code above. 到目前为止,这是我的代码,直到我希望输入上面的代码为止。 Using Eclipse IDE, if this is information is needed. 如果需要信息,请使用Eclipse IDE。

The point of the code is to save the numbers to the txt file and pull them back to read them, so they can be calculated. 代码的重点是将数字保存到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:");

Let's assume that you successfully read the file into the String and the numbers into an array of numbers and the path is an absolute path. 假设您已成功将文件读取到String中,并将数字读取到了数字数组中,并且该路径是绝对路径。

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

then you will create the .txt file on the location like this: 然后您将在以下位置创建.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();
}

Create a java.io.FileWriter object first, then create a java.io.PrintWriter based on that FileWriter object. 首先创建一个java.io.FileWriter对象,然后基于该FileWriter对象创建一个java.io.PrintWriter Then you can use PrintWriter.print() to add text to the file: 然后,您可以使用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");

Note that you'll need to encase this code in a try-catch block to handle IOExceptions : 请注意,您需要将此代码包装在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM