import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
上面是我当前尝试使用的代码,它编译得很好,然后我得到一个运行时错误:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
我已经用 google 搜索了该错误,但没有任何帮助(我只用 google 搜索了该错误的前 3 行)
基本上,我正在编写的程序是一个更大程序的一部分。这部分是从一个文本文件中获取信息,其写法如下:
电影一/1.5
电影二/1.3
电影三/2.1
电影四/4.0
文本是电影标题,浮点是电影的持续时间(将添加 20 分钟(用于广告),然后四舍五入到最接近的整数)
接下来,程序将信息放入数组中,以便可以从程序中轻松访问和修改它,然后写回文件。
我的问题是:
我当前遇到运行时错误,不知道如何修复? (目前我只是想读取每一行,并将其存储在一个数组中,作为程序其余部分的基础)任何人都可以指出我正确的方向吗?
我不知道如何在“/”处进行分割,我认为它类似于 .split(“/”)?
任何帮助将不胜感激!
扎克。
最佳答案
您的代码正在运行,但它只读取一行。您可以使用 bufferedReader 这是一个示例
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
这是一个拆分示例
class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
关于Java从文件读取到数组运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10040303/