简体   繁体   中英

Using 2 methods in one to read and write to file

I have written 2 methods - A write to method and a read from method. They work fine but I want to combine them so that they work like the pseudo code that I have written:

prompt user for input filename
open input file
prompt user for output filename
open output file
while there are lines in the input file
    read a line
    print it to screen
    writeit to the output file
close the input file
close the output file

I have tried a few different variations but I can't seem to get this to work?

Read to method:

 public void readFile() {
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    String InputFileName;
    String nextLine;

    clrscr();
    System.out.println("Please enter the name of the file that is to be READ (e.g. aFile.txt: ");
    InputFileName = Genio.getString();

    try {
        fileReader = new FileReader(InputFileName);
        bufferedReader = new BufferedReader(fileReader); 
        nextLine = bufferedReader.readLine();

        while (nextLine != null) {
            System.out.println(nextLine);
            nextLine = bufferedReader.readLine();
        }
    } catch (IOException e) {
        System.out.println("Sorry, there has been a problem opening or reading from the file");
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();    
            } catch (IOException e) {
                System.out.println("An error occurred when attempting to close the file");         }
        }  
    }
}

Write to method:

public void writeFile() {
    String myString;
    clrscr();
    System.out.println("Begin typing the contents to you wish to WRITE to file: ");
    myString = Genio.getString();
    System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    FileOutputStream outputStream = null;
    PrintWriter printWriter = null;

    try {
        outputStream = new FileOutputStream("writing.txt");

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

        System.out.println("File: 'writing.txt' has been saved with the contents above.\n\nYou can now open this file using the other options in the menu screen.");
        pressKey();
    } catch (IOException e) {
        System.out.println("Sorry, there has been a problem opening or writing to the file");
    } finally {
        if (printWriter != null)
            printWriter.close();    
    }
}   

The Genio 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);
 }
}

Here is your merged function readAndWrite() :

public static void readAndWrite() {
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;

    FileOutputStream outputStream = null;
    PrintWriter printWriter = null;

    String InputFileName, OutputFileName;
    String nextLine;

    clrscr();

    // Prompt user for input filename
    System.out.println("Please enter the name of the file that is to be READ (e.g. aFile.txt: ");
    InputFileName = Genio.getString();

    // Prompt user for output filename
    System.out.println("Please enter the name of the file that is to be WRITTEN (e.g. bFile.txt: ");
    OutputFileName = Genio.getString();

    try {
        // Open input file
        fileReader = new FileReader(InputFileName);
        bufferedReader = new BufferedReader(fileReader); 


        // Open output file
        outputStream = new FileOutputStream(OutputFileName);
        printWriter = new PrintWriter(outputStream);


        // Read a line
        nextLine = bufferedReader.readLine();

        // While there are lines in the input file
        while (nextLine != null) {
            // Print it to screen
            System.out.println(nextLine);

            // Write it to the output file + a new-line
            printWriter.write(nextLine+"\n");


            // Read a line
            nextLine = bufferedReader.readLine();
        }

        // Close the input file
        bufferedReader.close();

        // Close the output file
        printWriter.close();

    } catch (IOException e) {
        System.out.println("Sorry, there has been a problem opening or reading from the file");
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();    
            } catch (IOException e) {
                System.out.println("An error occurred when attempting to close the file");
            }
        }
        if(printWriter != null) {
            printWriter.close();
        }
    }
}

Let me know whether it works or not
Happy coding :) -Charlie

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