简体   繁体   English

读取文本文件的Java定界符

[英]Java delimiter reading a text file

I'm trying to read a text file with this format: 我正在尝试使用以下格式读取文本文件:

Array x
1,3,5,4

Array y
12,13,15,11

and put it in two array, but I only want the integer. 把它放在两个数组中,但我只想要整数。 What delimiter should I use to ignore the String and the empty line? 我应该使用什么分隔符来忽略String和空行?

Here's my code in putting the int to arrays. 这是将int放入数组的代码。 By the way, I'm using scanner to read the file: 顺便说一句,我正在使用扫描仪来读取文件:

Scanner sc = null;

     try
     {
     sc = new Scanner(new FileInputStream("C:\\x.txt"));
     sc.useDelimiter("");  // What will I put inside a quote to get only the int values?
     }
     catch(Exception e)
     {
     System.out.println("file not found!");
     }
int[] xArray = new int[4];
int[] yArray = new int[4];

     while (sc.hasNextInt( )){
         for(int i=0; i<4; i++){
            xArray[i] = sc.nextInt( );
        }
         for(int i=0; i<4; i++){
            yArray[i] = sc.nextInt( );
        }
    }

What I want to get is 我想得到的是

int[] xArray = {1,3,5,4}
int[] yArray = {12,13,15,11}

I hope you understand :) 我希望你明白 :)

Thanks. 谢谢。

I suggest you to use bufferedreader instead of scanner. 我建议你使用bufferedreader而不是扫描仪。 You can use below code : 您可以使用以下代码:

BufferedReader br=new BufferedReader(new FileReader("your file name"));
br.readLine(); //it will omit first line Array x
String x=br.readLine(); //it return second line as a string
String[] x_value=x.split(","); //You can parse string array into int.

This is for Array x. 这适用于Array x。 You can do the same for array y. 您可以对阵列y执行相同的操作。 and after that parse into int. 之后解析为int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM