[英]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"); [这是catch语句] System.out.println(“错误的异常”); } }
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; 将扫描过程与I / O过程分开; keep the try
blocks as small as possible. 保持try
块尽可能小。
Second, to get a path to a file, use Paths.get()
: 其次,要获取文件的路径,请使用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-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 closes your resources for you right after the try block (ie, after the first pair of curly brackets). Java在try块之后(即在第一对大括号之后)立即为您关闭资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.