Andrew J Winkler Andrew J Winkler - 2 months ago 8
Java Question

User input into a text file in java

I want a user to be able to copy and paste multi-line text into the console and then save it to a specific text file ("weather.text" in this case which is located in a data folder within the same package). I've been working on this simple task for a few hours and the solution is evading me. I'm new to java so I apologize in advance.

This static function is called from the main launcher class.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Scanner;

public static void writeFile()
{
//set up for the user input
Reader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
String str = null;

try {
//prompt the user to input data
System.out.println("Type or paste your data and hit Ctrl + z");
str = br.readLine();

//save the user input data to text file
PrintWriter writer = new PrintWriter("weather.txt", "UTF-8");
writer.print(str);
writer.close();

} catch (IOException e) {
e.printStackTrace();
}

}


currently I'm experiencing 2 problems.

1) The code above seems to only save the first line pasted into the console into the console.

2) The text file being saved is in the global project folder and not the specified data sub folder.

Any help or suggestions are appreciated. Thank you.

Answer

You are writing str, but str is just the first line in br You have to read all lines in a loop.

Try this code:

   public static void writeFile()
{
    //set up for the user input
    Reader r = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(r);
    String str = null;

    try {
            //prompt the user to input data
            System.out.println("Type or paste your data and hit Ctrl + z");
            PrintWriter writer = new PrintWriter("weather.txt", "UTF-8");
            while((str = br.readLine())!=null)
            {
            //save the line

            writer.println(str);
            }
            writer.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

about the second issue, the file is written in the working directory of your application.