简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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