获取错误“;此方法必须返回类型为java.lang.String的结果;
假设获取错误“;此方法必须返回类型为java.lang.String的结果;,java,return-value,Java,Return Value,假设file.txt只包含“Hello”。当我编译Java代码时,它显示 错误:此方法必须在第5行中返回类型为java.lang.String的结果 当我在readTxt函数中打印时,它可以显示“Hello”。 我已经检查了结果是否为正确的字符串类型,但它也显示了编译器错误。如何将返回值设置为main函数 import java.io.*; import java.lang.String; public class ReadTxtFile { public static String read
file.txt
只包含“Hello”。当我编译Java代码时,它显示
错误:此方法必须在第5行中返回类型为java.lang.String的结果
当我在readTxt
函数中打印时,它可以显示“Hello”。
我已经检查了结果是否为正确的字符串类型,但它也显示了编译器错误。如何将返回值设置为main函数
import java.io.*;
import java.lang.String;
public class ReadTxtFile {
public static String readTxt(String filePath) {
try {
File file = new File(filePath);
if(file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
lineTxt = br.readLine();
//System.out.println(lineTxt);
br.close();
return lineTxt;
} else {
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
String filePath = "C:/file.txt";
String fileword = readTxt(filePath);
System.out.println(fileword);
}
}
您承诺从方法返回字符串,因此现在必须这样做。实现这一承诺的唯一方法是抛出一个异常
public static String readTxt(String filePath) { // Here you promise to return a String
try {
...
if(file.isFile() && file.exists()) {
...
return lineTxt; // Here you return a String as promised
} else {
// Here you're missing either return or throw
}
} catch (Exception e) {
// Here you're missing either return or throw
}
}
这从根本上说是一个设计问题——如果由于某种原因无法读取文件,您的方法应该怎么做?返回一个特殊字符串,如“Error”?返回null
?失败、抛出和异常?还有别的吗
你自己回答这个问题,你就会清楚如何修复代码。有几种最佳做法可以防止将来出现错误。我试着去报道他们。不是说我的是完美的,但你会明白的
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class StackOverFlow {
public static void main(String[] args) {
try {
String sText = getFileText("C:/file.txt");
System.out.println("Text is: " + sText);
} catch (FileNotFoundException e) {
System.out.println("File not Found");
} catch (IOException e) {
System.out.println("@Error while reading text: " + e.getMessage());
}
}
private static String getFileText(String filePath) throws FileNotFoundException, IOException {
File file = new File(filePath);
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
}finally {
reader.close();
}
return new String(stringBuilder);
}
}
如果
file.isFile()&&file.exists()
为false,会发生什么情况?可能会将其更改为显示文件不存在
在不处理它的情况下从不捕获异常。不要捕获所有异常的基类。仅捕获已检查的例外情况在例外情况结束时,您不返回任何内容,以防您进入其他路径