Java异常处理和文件I/O

Java Exception Handling and File I/O

本文关键字:文件 异常处理 Java      更新时间:2023-09-26
  [ 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("错误异常");}

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

}

如果有人能帮我,我将不胜感激。

没有人可以为你写完整的代码。然而,这里有一些提示:

保持链接始终打开。

将扫描进程与I/O进程分离;保持try块尽可能小。

第二,获取文件的路径,使用Paths.get():
final Path path = Paths.get(someString);

检查文件是否存在,使用:

Files.exists(path);

打开阅读器以文本(非二进制)形式读取文件,使用:

Files.newBufferedReader(path, StandardCharsets.UTF_8);

打开一个写入器将文件写入文本(非二进制),使用:

Files.newBufferedWriter(path, StandardCharsets.UTF_8);

使用try-with-resources语句:

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在try块之后(即在第一对花括号之后)为您关闭资源。