Java异常处理和文件I / O.

时间:2014-03-17 23:57:10

标签: java javascript file-io exception-handling fileinputstream

  [ 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
    {

[这是catch语句] System.out.println("错误的例外");         }

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

}

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

1 个答案:

答案 0 :(得分:1)

没有人可以为您编写完整的代码。但是,这里有一些提示:

Keep that link open at all times

将扫描过程与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块之后立即关闭你的资源(即在第一对花括号之后)。