Java从文件读取到数组运行时错误
上面是我当前尝试使用的代码,它编译得很好,然后我得到一个运行时错误:Java从文件读取到数组运行时错误,java,file-io,Java,File Io,上面是我当前尝试使用的代码,它编译得很好,然后我得到一个运行时错误: 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("film
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();
}
}}
我用谷歌搜索了错误,没有任何帮助(我只搜索了错误的前3行)
基本上,我正在写的程序是一个更大程序的一部分。这一部分是从一个文本文件中获取信息,该文件的编写方式如下:
胶片1/1.5电影二/1.3
电影三/2.1
电影4/4.0 文本是电影标题,浮动是电影的持续时间(将添加20分钟(用于广告),然后将四舍五入到最接近的整数) 接下来,程序将把信息放入一个数组中,这样就可以很容易地从程序中访问和修改信息,然后将其写回文件 我的问题是: 我当前收到一个运行时错误,不知道如何修复?(目前我正在尝试读取每一行,并将其存储在一个数组中,作为程序其余部分的基础)有人能给我指出正确的方向吗 我不知道如何在“/”处进行拆分,我想它类似于.split(“/”) 任何帮助都将不胜感激
Zack.您的代码正在工作,但它只读取一行。您可以使用bufferedReader,下面是一个示例
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)
下面是一个拆分示例类StringSplitExample{
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());
}
}
}
公共静态void main(字符串[]args){
String st=“Hello\u World”;
字符串str[]=st.split(“”);
对于(int i=0;i }
我不会使用用于标记化的扫描仪(一次只能得到一个单词或符号)。您可能只想使用具有readLine
方法的BufferedReader
,然后按照您的建议使用line.split(“/”)
将其拆分为两部分。惰性解决方案:
扫描仪扫描=
scan.nextLine()
你的代码对我来说很好。我没有得到一个NoTouchElementException
,我也不知道您的代码是如何生成的。
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]);
}
}
}