用Java读取文件。我得到“FileNotFound”异常。 例外:
java.io.FileNotFoundException: something.txt (The file was not found)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at rmihello.ReadStringFromFileLineByLine.main(ReadStringFromFileLineByLine.java:13)
即使我的文件位于我的源代码旁边的bin中: 我也尝试过给我文件的整个路径,例如
path = "C:/Users/Alexander/Desktop/java/something.txt"
或
path = "cd 'C:/Users/Alexander/Desktop/java/something.txt'"
所有这一切都失败了 这是我的代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
String path = "something.txt";
File file = new File(path);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
正如评论中所提到的,您的代码应该像这样开始:
Path file = ; //Specify the path to your file
查看Reading, Writing, and Creating Files in Java了解更多信息
修改强>
只需像这样编辑你的代码就可以了。
public static void main(String[] args){
String path = "C://Something.txt"; // I put the file under the C: path in my example
try {
File file = new File(path);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
然后只需更改路径以适合您的路径。
答案 1 :(得分:0)
相对路径增加了文件未找到的不确定性。 在尝试替代方案时,请处理错误:
File file = new File("C:/.../something.txt");
try {
...
} catch (FileNotFoundException e) {
File full = file.getAbsoluteFile();
File dir = file.getParentFile();
while (dir != null && !dir.exists()) {
dir = dir.getParentFile();
}
System.out.printf("File %s does not exist under %s%n",
full.getPath(),
dir == null ? "/" : dir.getPath());
} catch (IOException e2) {
}
提示:
StringBuilder
更快,是StringBuffer的继承者。
新风格(自Java 7起):
Path path = Paths.get("C:/...");
byte[] content = Files.readAllBytes(path);
String contentText = new String(content); // Default encoding
答案 2 :(得分:-1)
如果您将文本文件插入名为text_files的文件夹中,则可以使用
访问它文件f =新文件(“text_files / something.txt”);