1,105,594 Community Members

Write text from user to file

Member Avatar
jad0521
Newbie Poster
4 posts since Apr 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi,
I'm trying to write a program that asks the user to enter a series of text lines and then stop and write those lines into a text file.
I tried to use this:

String newFileName;
String line;
PrintWriter outputStream = new PrintWriter(newFileName);
while( line.length()>0){
line = keyboard.next();
outputStream.println(line);
}
But the while loop does not stop when the user enters an empty line (which by the way I have no idea what it is and how java recognize an empty line. help with that is also appreciated)

any other ways to do this? (take input from user and write it to a file)
thanks a million

Member Avatar
BestJewSinceJC
Posting Maven
2,760 posts since Sep 2008
Reputation Points: 700 [?]
Q&As Helped to Solve: 366 [?]
Skill Endorsements: 17 [?]
 
0
 

The next() method doesn't get an entire line of text, it only gets the next token, which by default, matches whitespace. So if you're reading in English sentences, it will have the effect of reading in a word at a time, not an entire sentence. The nextLine() method can be used to get the entire line of text, not including the newline character \n. And you can use the String class's equals() method to test whether or not the user simply clicked enter without typing anything else.

public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<String> list = new ArrayList<String>();
		Scanner keyboard = new Scanner(System.in);
		while (keyboard.hasNextLine()){
			String s = keyboard.nextLine();
			list.add(s);
			if (s.equals("")) break;
		}
	}
Member Avatar
jad0521
Newbie Poster
4 posts since Apr 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thank yoou so much for the reply.
I still have a problem in how I write the user line into a .txt file using PrintWriter class?

   String fileName = "out.txt"; // name of file we will create
        try {
            PrintWriter outputStream = new PrintWriter(fileName);
            outputStream.println("This is the first line ");
            outputStream.println("This is second line.");
            outputStream.println("--------- LAST LINE FROM PROGRAM ");
            outputStream.close();
            System.out.println("Those lines were written to " + fileName);
        } // try
        catch (FileNotFoundException e) {
            System.out.println("Error opening the file " + fileName);
        } // catch
    } // method

I have this sample from the teacher but that is "constant string to a file". When I ask the user to enter a line of text I don't know how to write that line to a file. Plus, when the user enters an empty line (or just pushed 'enter', I want the while loop to stop.
When i used nextLine(), it does not wait for the user to enter another line, it passes the while loop!
I'm a beginner and don't really know what to do with this final homework
your help is highly appreciated,
thanks a million again

Member Avatar
jad0521
Newbie Poster
4 posts since Apr 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

WHY THE LOOP IN THIS METHOD DOES NOT WORK?

public static void writeToFile(String fileName){
System.out.println("Write your text in the form of lines:");
String line = " ";
    try {               
    PrintWriter outputStream = new PrintWriter(fileName);
       while (!line.equals("")){
        outputStream.println(line);
        line= keyboard.nextLine();  
      }//while
    outputStream.close();
        }//try
    catch (FileNotFoundException e) {
    System.out.println("Error " + e.getMessage());
    } // catch
}//end method writeToFile

it is supposed to take a line from user, and print/write it in the PrintWriter outputStream, but it does not take input at all!
can you help me figure out what's wrong with it?
thank you so very much.

Member Avatar
BestJewSinceJC
Posting Maven
2,760 posts since Sep 2008
Reputation Points: 700 [?]
Q&As Helped to Solve: 366 [?]
Skill Endorsements: 17 [?]
 
0
 

Why don't you post all of your relevant code. In the code you provided above, you never created a Scanner, hence you cannot invoke the Scanner class's nextLine() method. Besides which, the example I gave you in post #2 can be easily modified to print the line out to a File instead of adding the line to the ArrayList.

Member Avatar
jad0521
Newbie Poster
4 posts since Apr 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 
package lab11Files;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter ;
import java.io.FileNotFoundException ;
import java.util.Scanner ;

public class lab11NoChar{
    public static Scanner keyboard  = new Scanner(System.in);  //Scanner object to read input

    public static void main(String[] args) {
        int userChoice=0;

        while (userChoice != 4) {
            System.out.println("");
            printMenu();
            userChoice= getInteger();

            if (userChoice == 4){
                System.out.print("Thank you for using the program.");
            }
            else if (userChoice== 1){
                System.out.print("Enter the name of the file you want to create: ");
                String newFileName = getFileName();
                writeToFile(newFileName);//THIS IS THE METHOD THAT I AM HAVING TROUBLE WITH
            }// user choice = 1

            else if (userChoice == 2){
                System.out.print("Enter the name of the file you want to Read from: ");
                String newFileName = getFileName();
                ReadfromFile(newFileName);
            }
            else if ( userChoice== 3){
                System.out.print("Enter the name of the file you want to append to: ");
                String newFileName = getFileName();
                appendToFile(newFileName);
            }
        }
    }

    //This method accepts input only from the menu list, otherwise it keeps asking for a correct input
    public static int getInteger () {

        int inputNum=0;    // number entered by the user
        boolean go = true; // as long as 'go' is true, ask the user for input
        while (go) {

            try {
                inputNum = keyboard.nextInt();
                if ((inputNum == 4)||(inputNum == 3)||(inputNum == 2)|| (inputNum == 1)){
                    go = false; // if we get here, the input was good
                }else {
                    System.out.print("You entered "+inputNum+" ! Only numbers from 1 to 7 are accepted! try again: ");
                    go = true;
                }
            } // end try    

            catch (Exception e){
                // read to end of line, to advance beyond the bad input, 
                String junk = keyboard.nextLine();
                System.out.print("Invalid input (" + junk + ").  Please try again: ");
            } // end catch
        } // end while

        return inputNum;
    }
    // this method writes the input lines into the file 'fileName' and stops when the user enters an empty line (when the user hits 'enter' twice)
    public static void writeToFile(String fileName){
        System.out.println("Write your text in the form of lines:");
        String line = " ";

        try {               
            PrintWriter outputStream = new PrintWriter(fileName);

            while (line.length() != 0){
                outputStream.println(line);
                line= keyboard.nextLine();

            }//while
            outputStream.close();
            System.out.print("Open the file " + fileName + " to read your text.");
        }//try

        catch (FileNotFoundException e) {
            System.out.println("Error opening the file " + fileName + e.getMessage());
        } // catch
    }//method write to file
    // this method prints the menu for the user to choose from
    public static void printMenu() {
        System.out.println("");
        System.out.print("What would you like to do? (Please enter a choice from the list)");
        System.out.println("");
        System.out.println("1- Create a new file for writing text (overwrite if file exists)");
        System.out.println("2- Read from a text file");
        System.out.println("3- Open an existing file for appending text at the end (create file if it doesn’t exist)");
        System.out.println("4- Quit this program");
        System.out.print("Please enter your selection: ");
    }// method print menu
    //this method asks the user to enter the name of the file to write to/ read from /or append to, and it concatenates that file name with '.txt' 
    public static String getFileName(){
        String extension = ".txt";
        String fileName = keyboard.next()+ extension;
        return fileName;
    }// method getFileName
    public static void ReadfromFile(String fileName)
    {
        Scanner inputStream = null;
        System.out.println("The file " + fileName + " contains the following lines:\n");
        try {
            inputStream = new Scanner(new File(fileName));
            while (inputStream.hasNextLine()) {
                String line = inputStream.nextLine();
                System.out.println(line);
            }
            inputStream.close();
        } 
        catch (FileNotFoundException e) {
            System.out.println("Error " + e.getMessage() + ". Cannot find  " + fileName);
        } // catch
    }
    public static void appendToFile(String fileName){
        System.out.println("Write your text in the form of lines to Append to file :");
        String line = " ";
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(input);

        try{
            // Create file 
            FileWriter fstream = new FileWriter(fileName,true);
            BufferedWriter out = new BufferedWriter(fstream);
            ///
            while ( !line.isEmpty() ){
                try {
                    line = reader.readLine();
                    out.newLine();
                    out.append(line);
                } catch (IOException e) {
                    System.err.println("Error: " + e.getMessage());
                }
            }
            //Close the output stream
            out.close();
            }catch (Exception e){//Catch exception if any
              System.err.println("Error: " + e.getMessage());
            }
    }
}
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article