使用resourceloader加载文本文件时的Java NoSuchElementException

时间:2018-05-15 19:49:49

标签: java java.util.scanner inputstream nosuchelementexception

im using resource loader to save the file into jar file (click here to open the image)

it is working perfectly fine is i remove the while(f.hasnext() { .... } I couldn't figure out what is going wrong I am trying to load the text file into jar file so, I am reading it through inputstream (click here to open the image)

this is the text file which i am loading

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

 public class Main {

 public static void main(String[] args) throws FileNotFoundException {

      ArrayList<morse> mkey = new ArrayList<>();
      encription e = new encription();

            morse.load(mkey);


 }


}

的ResourceLoader

 import java.io.IOException;
    import java.io.InputStream;

    final public class ResourceLoader {

    static ResourceLoader rl = new ResourceLoader();

    public static InputStream rload(String path) {
        InputStream input = rl.getClass().getResourceAsStream(path);

        return input;
    }
    }

莫尔斯电

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
final public class morse {

    String c;
    String symbol;
     public static void  load(ArrayList<morse> mkey) throws FileNotFoundException
     {      
         Scanner f = new Scanner( ResourceLoader.rload("morse key.txt"));
         int i=0;
        while(f.hasNext()) {
            morse temp =new morse();

            temp.c =f.next();
            temp.symbol = f.n;
            mkey.add(temp);
            System.out.println(mkey.get(i).c  );
            //f.nextLine();
            i++;

        }
         f.close();      
     }

}

文本文件

0 ----- 1 .---- 2 ..--- 3 ...---- 4 ....- 5 ..... 6 -.... 7 --... 8 --- .. 9 ----。 一个 。- b -... C -。-。 d - .. e。 F ..-。 G - 。 H .... 一世 .. j .--- k -.- l .- .. 米 - n - 。 o --- p .--。 q --.- r .-。 s ... t - 你..- v ...- w .-- X -..- y -.-- z - ..

1 个答案:

答案 0 :(得分:0)

正如我最初在评论中所写,而不是两次调用f.next(),只需读取整行一次并将字符串拆分为temp.c和temp.symbol。