【问题标题】:Java Exception Handling and File I/OJava 异常处理和文件 I/O
【发布时间】:2014-03-17 23:57:10
【问题描述】:
  [ 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]
}

}

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

【问题讨论】:

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


    【解决方案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 块之后(即第一对大括号之后)立即为您关闭资源。

    【讨论】:

      猜你喜欢
      • 2013-01-07
      • 2015-01-17
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多