如何在 try catch 中使用 BufferedReader?
How to use BufferedReader in a try catch?
我已经尝试使用 bufferedreader 好几次了,但每次我都会遇到一些表单错误。现在是 "not a statement" 和“;预计”也是 "catch without try" 的时候了。我在 try(bufferedreader) 行中不断收到错误。我使用这个正确吗?我只是尝试一下,不太确定它是如何工作的。从我一直在查看我的代码的在线资源看起来不错。但是当我 运行 我自己的时候它给我错误。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Problem2 {
public static void main(String [] args) {
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(New FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
}
br.close();
}
catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
}
}
1) 错误很简单,首先你应该使用 new FileReader
(小写 n
)而不是 New FileReader
(大写 N
)。
2) 在将 catch
处理程序附加到 try
块之前,您要关闭 else
块。
我现在已经更正了这两个问题,下面的代码应该可以编译。
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
br.close();
}catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
我已经尝试使用 bufferedreader 好几次了,但每次我都会遇到一些表单错误。现在是 "not a statement" 和“;预计”也是 "catch without try" 的时候了。我在 try(bufferedreader) 行中不断收到错误。我使用这个正确吗?我只是尝试一下,不太确定它是如何工作的。从我一直在查看我的代码的在线资源看起来不错。但是当我 运行 我自己的时候它给我错误。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Problem2 {
public static void main(String [] args) {
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(New FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
}
br.close();
}
catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
}
}
1) 错误很简单,首先你应该使用 new FileReader
(小写 n
)而不是 New FileReader
(大写 N
)。
2) 在将 catch
处理程序附加到 try
块之前,您要关闭 else
块。
我现在已经更正了这两个问题,下面的代码应该可以编译。
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
br.close();
}catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}