Create method that opens a file, then lets’s user write to file then end when pressing enter on empty line?

I want to create a method that which opens a file for writing, then prompts the user to enter lines of text until they press enter on an empty line to stop input.

It’s giving some trouble in that I can get the method run and I can input text but it wont close or save? I hit return after my text to go to a blank line and hit return again but it just moves onto another line.

I have written the following but can’t get it working correctly.

My code:

 public void writeFile()
{
    String myString;
    clrscr();
    System.out.println("Begin typing: ");
    myString = Genio.getString();
    FileOutputStream outputStream = null;
    PrintWriter printWriter = null;
    // use a try-catch-finally block to catch file-related exceptions
    try
    {
        outputStream = new FileOutputStream("writing.txt");
        printWriter = new PrintWriter(outputStream); 
        printWriter.write(myString);
        printWriter.newLine();
        // write information to the file via the PrintWriter
        while (myString  != "")
        {
            printWriter.print(myString + " ");
        }
    }
    catch (IOException e)
    {

        System.out.println("Sorry, there has been a problem opening or writing to the file");
    }
    finally
    {

        if (printWriter != null)
        {
            printWriter.close();    
        }
    }
}   

If it’s needed, Genio is the class that deals with user input:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Genio
{

public Genio()
{
}

private static String getStr() 
{
    String inputLine = "";
    BufferedReader reader = 
        new BufferedReader(new InputStreamReader(System.in));
    try 
    {
        inputLine = reader.readLine();
    }

    catch(Exception exc) 
    {
        System.out.println ("There was an error during reading: "
                            + exc.getMessage());
    }
    return inputLine;
}

public static int getInteger()
{
    int temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Integer.parseInt(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Integer value needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);
    return(temp);
 }

public static float getFloat()
{
    float temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Float.parseFloat(keyboard.readLine());
            OK = true;
        }


        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Number needed: ");
            } 
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

public static double getDouble()
{
    double temp=0;
    boolean OK = false;
    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Double.parseDouble(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Number needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

 public static char getCharacter()
 {
     String tempStr="";
     char temp=' ';
     boolean OK = false;
     do 
     {
         try
         {
             tempStr = getStr();
             temp = tempStr.charAt(0);
             OK = true;
         }

         catch (Exception eRef)
         {
             if (eRef instanceof StringIndexOutOfBoundsException)
             {
                 // means nothing was entered so prompt ...
                 System.out.print("Enter a character: ");
             }            
             else 
             {
                 System.out.println("Please report this error: "+eRef.toString());
             }
         }

     } while(OK == false);

     return(temp);
 }

 public static String getString()
 {
    String temp="";
    try
    {
        temp = getStr();
    }
    catch (Exception eRef)
    {
        System.out.println("Please report this error: "+eRef.toString());
    }
    return(temp);
 }     
}

Answer

You class works fine for the most part. I fixed the problematic part for you:

// write information to the file via the PrintWriter
while (!myString.equals(""))
{
    myString = Genio.getString();
    printWriter.print(myString + "n");
}

First the condition inside the while was incorrect. MyString has to be compared using the equals operator (or using the isEmpty method).

Second, you need to keep reading into myString inside the loop, otherwise you get an infinite loop and it will never exit.

Third, you want want to add newlines to the output file, so I added them.

Leave a Reply

Your email address will not be published. Required fields are marked *