的Java从文件中读取到阵列运行时错误

问题描述:

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(); 
     } 
    }} 

以上是我目前正在尝试使用的代码,它编译罚款,然后我得到的运行时错误:我GOOGLE了的Java从文件中读取到阵列运行时错误

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) 

错误,没有任何帮助(我只搜索错误的前3行)

基本上,我正在编写的程序是更大程序的一部分。这部分是从哪个是这样写的文本文件获取信息:

电影一个/ 1.5
电影二/ 1.3
电影三/ 2.1
电影四/ 4.0

与文本之中电影片名和浮动片是电影的持续时间(将会有20分钟的时间添加到它(对于广告),然后将四舍五入到最接近的整数)

继续前进,程序然后把数组中的信息,因此可以访问& modifie d很容易从程序中,然后写回到文件中。

我的问题是:

我得到一个运行时错误目前,没有线索如何解决? (目前我只是想读取每一行,并将其存储在一个数组中,作为程序其余部分的基础)任何人都可以指向正确的方向吗?

我不知道如何在“/”分裂我认为这是像.split(“/”)?

任何帮助将不胜感激!

Zack。

+1

你的代码适合我。我没有'NoSuchElementException',我看不到你的代码是如何生成的。 – 2012-04-06 07:17:51

您的代码工作,但它只是读取一行。你可以在这里使用的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]); 
       } 
     } 
}

我不会用一个Scanner,那是符号化(你一次只能得到一个单词或符号)。您可能只想使用BufferedReader,它有一个readLine方法,然后使用line.split("/"),因为您建议将其分成两部分。

懒惰溶液:

扫描仪扫描= ..;
scan.nextLine();