在一个中使用2个方法来读取和写入文件

时间:2014-11-18 17:11:21

标签: java

我写了2个方法 - 写入方法和读取方法。它们工作正常,但我想将它们组合起来,使它们像我写的伪代码一样工作:

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

我尝试了一些不同的版本,但我似乎无法让它发挥作用?

阅读方法:

 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");         }
        }  
    }
}

写入方法:

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();    
    }
}   

处理用户输入的Genio类:

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

1 个答案:

答案 0 :(得分:1)

以下是您合并的函数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();
        }
    }
}

让我知道它是否有效 快乐编码:) -Charlie