如何从文本中读取行?看看我的代码:
public static String getTemplateFromFile() {
String name = null;
try {
BufferedReader reader = new BufferedReader(new
FileReader(
"http://localhost:8080/blog/resources/cache/templateName.txt"));
name = reader.readLine();
//name="TEST";
//NULL anyway
reader.close();
}
catch (Exception e) {
}
return name;
}
Run Code Online (Sandbox Code Playgroud)
我也有secnod版本,但我的服务器冻结了.
public static String getTemplateFromFile() {
String name = null;
/*
try {
URL url = new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
Scanner s = new Scanner(url.openStream());
name=s.nextLine();
s.close();
}
catch(IOException ex) {
ex.printStackTrace();
}*/
return name;
}
Run Code Online (Sandbox Code Playgroud)
我认为它无法关闭连接或其他什么.即使我name="TEST";在尝试构造中说它也返回NULL .
FileReader就是这样 - 一个从文件中读取的类,而不是HTTP请求.
您将获得无效的文件路径异常,然后您将在您的邪恶空catch块中忽略它.
相反,你应该使用URLConnection.