我已经在同一个文件夹中声明了文件,但它给了我一个“File NotFound Exeption”。文件名是正确的。如果我尝试使用其他方法访问文件信息,我会得到同样的错误。我不知道为什么.是否存在逻辑错误。我从网站http://www.vogella.com/articles/JavaIO/article.html中了解到>
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FilesC {
public static void main(String[] args)
{
String returnValue = "";
FileReader file = null;
String fileName = "test.txt";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
}
}
谢谢它有效,但还有一件事>我的文件中只有一行。当我对我的代码执行以下操作时
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FilesC {
public static void main(String[] args)
{
String returnValue = "";
FileReader file = null;
String fileName = "C:\\Users\\KingKong\\Desktop\\WorkSpace\\Victory\\src\\test.txt";
String line = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
System.out.println(line);
System.out.println(returnValue);
}
}
它给了我输出:
null
myLine
这怎么可能。如果只有一行,那么该行和 returnValue 是否必须具有相同的值?