xpoiled7
xpoiled7

Reputation: 23

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?

Here's my code in putting the int to arrays. 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.

Upvotes: 0

Views: 7934

Answers (1)

Vimal Bera
Vimal Bera

Reputation: 10497

I suggest you to use bufferedreader instead of scanner. 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. You can do the same for array y. and after that parse into int.

Upvotes: 2

Related Questions