简体   繁体   中英

Java Exception Handling and File I/O

  [ I am out of ideas I need a to write a code that writes and reads text files within  theprocessfiles method and a code that counts and print the total number of borrowers As part of my home I need to write a class that writes and reads text files.


public void 

processFiles()throws FileNotFoundException
{
     [ I am struggling to write a code that actually reads and writes a text file to a windows explorer folder ]

    try
    { 
        System.out.println("Enter your Firstname");
        Scanner sc=new Scanner(System.in); 
        String firstName=sc.nextLine();   
        System.out.println("Enter your lastname");
        String lastName=sc.nextLine();
        System.out.println("Enter your library number"); 
        String libraryNumber=sc.nextLine(); 
        System.out.println("Enter the number of books on loan");
        int numberOfBooks=sc.nextInt();
        System.out.println(firstName  +" "+ lastName +" "+ libraryNumber +" "+ numberOfBooks);
        int count// I am struggling to to write a code that counts the borrowers and diplay it on the windows page.
        int total// I am struggling to to write a code that displays the total number of borrowers to the windows page.
        input.close();
        output.close();
    }
    catch (InputMismatchException e)  [This is the catch method]
    { 
        System.out.println("Invalid");
    }
    catch (Exception e) this is the catch method
    {

[ this is catch statement ] System.out.println("Wrong exception"); }

    input.close();[ this is the input close]
    output.close(); [and output close statements]
}

}

[I would be much appreciated if anyone could help me with this.]

Nobody can write the full code for you. However, here are a few tips:

Keep that link open at all times .

Separate the scanning process from the I/O process; keep the try blocks as small as possible.

Second, to get a path to a file, use Paths.get() :

final Path path = Paths.get(someString);

To check whether a file exists, use:

Files.exists(path);

To open a reader to read a file as text (NOT binary), use:

Files.newBufferedReader(path, StandardCharsets.UTF_8);

To open a writer to write a file as text (NOT binary), use:

Files.newBufferedWriter(path, StandardCharsets.UTF_8);

Use the try-with-resources statement:

try (
    // open I/O resources here
) {
    // operate with said resources
} catch (FileSystemException e) {
    // fs error: permission denied, file does not exist, others
} catch (IOException e) {
    // Other I/O error
}

Java closes your resources for you right after the try block (ie, after the first pair of curly brackets).

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