gpt4 book ai didi

java - 使用 FileReader 时解决 IOException、FileNotFoundException

转载 作者:行者123 更新时间:2023-11-29 10:15:32 29 4
gpt4 key购买 nike

我无法解决以下代码中的以下异常。我使用 BufferedReader 的方式有什么问题?我在 main 方法中使用 BufferedReader

输出:-

ParseFileName.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown 

BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));

// ParseFileName  is used to get the file name from a file path 
// For eg: get - crc.v from "$ROOT/rtl/..path/crc.v"

import java.util.regex.Pattern;
import java.io.*;

public class ParseFileName {

//Split along /'s , and collect the last term.
public String getName (String longName) {
String splitAt = "/";
Pattern pattern1 = Pattern.compile(splitAt);
String[] parts = pattern1.split(longName);
System.out.println("\nparts.length = " + parts.length);

//Return the last element in the array of strings
return parts[parts.length -1];
}

public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();

}

}

更新:以下作品:

public static void main(String[] args) throws FileNotFoundException, IOException { 

但是 try..catch 仍然有一些困扰我的问题:

try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex2) {
ex2.printStackTrace();
}

buffread dosent 好像是得到了文件名。我收到此错误:

javac ParseFileName.java ParseFileName.java:67: cannot resolve symbol

符号:变量 buffread

location: class ParseFileName

while ((line = buffread.readLine())!= null) {

最佳答案

在方法的 header 中添加 throws FileNotFoundException, IOException。看起来只要抛出 IOException 就可以解决您的问题,但是将两者结合起来可以让您判断文件的存在是否存在问题,或者是否出现了其他问题(请参阅下面的 catch 语句)。

public static void main(String[] args) throws FileNotFoundException, IOException { 

或者,如果您想捕获一个特定的异常并对其进行处理:

try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
// Do something with 'ex'
} catch (IOException ex2) {
// Do something with 'ex2'
}

更新以解决更新后的问题:这只是一个简单的范围问题,可以通过在 try 语句之外声明 BufferedReader 来解决。

BufferedReader buffread = null;
try {
buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
...

关于java - 使用 FileReader 时解决 IOException、FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18968709/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com