F.Helix
F.Helix

Reputation: 47

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. 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. 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.

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.

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:");

Upvotes: 0

Views: 440

Answers (2)

Jonah Haney
Jonah Haney

Reputation: 521

Create a java.io.FileWriter object first, then create a java.io.PrintWriter based on that FileWriter object. Then you can use PrintWriter.print() to add text to the file:

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 {
    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

Upvotes: 1

Jakub Balhar
Jakub Balhar

Reputation: 315

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 nameOfTheFile = "/absolute/path";
int[] numbersToStore = new int[]{1,2,3,4,5};

then you will create the .txt file on the location like this:

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

Upvotes: 1

Related Questions