抱歉,如果这是一个显而易见的问题,但我似乎无法理解。我正在做数据结构课程的作业。它涉及从简单的 .dat 文件中提取数据。我们以前从未使用过 Java 中的任何文件访问选项,因此教授只是为我们提供了该部分的工作代码。
一个类叫做FileReadExample
创建一个新的BufferedReader
对象,打开一个文件,然后应该踢出有关该文件的一堆数据。
但我根本无法访问任何数据。
在单独的testMain
文件,我创建了一个新的FileReadExample
对象命名fr
然后尝试打印出类似的东西fr.readLine()
从那里开始,但它告诉我没有这样的方法。
我确信我错过了一些非常简单的东西。
教授的代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReadExample
{
public static void main(String[] args)
{
System.out.println("got here");
try
{
BufferedReader in = new BufferedReader(new FileReader(new File("sample-file.dat")));
System.out.println("File open successful!");
int line = 0;
for (String x = in.readLine(); x != null; x = in.readLine())
{
line++;
System.out.println(x);
if (line <= 3)
{
String[] tokens = x.split(" ");
System.out.println("Number of tokens in line " + line + ": " + tokens.length);
System.out.println("The tokens are:");
for (String token : tokens)
{
System.out.println(token);
}
}
else
{
String[] tokens = x.split("\\|");
System.out.println("Number of tokens in line " + line + ": " + tokens.length);
System.out.println("The tokens are:");
for (String token : tokens)
{
System.out.println(token);
}
Integer[] values = new Integer[tokens.length];
Integer sum = 0;
for (int i = 0; i < tokens.length; i++)
{
sum += Integer.parseInt(tokens[i]);
}
System.out.println("Sum: " + sum);
}
}
} catch (IOException e)
{
System.out.println("File I/O error!");
}
}
}
Thanks.
尝试读取文件:
BufferedReader reader = null;
try {
File file = new File("sample-file.dat");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)