ttwis
ttwis

Reputation: 378

Reading from a .txt file in java

I have a .txt file with some numbers. It looks like this:

1 4364 658 4328 666
2 5109 659 5100 638
3 4936 659 4904 677
4 4936 659 4957 639
5 5518 660 5602 672

I need to extract all numbers, except first column (1, 2, 3, 4, 5 ...), and use them for further calculation. Any help, tip would help a lot.

Upvotes: 0

Views: 944

Answers (7)

See the RandomAccesFile and the int Wrapperclass Integer

    RandomAccesFile f = new RandomAccessFile("file.txt", "r"); // r=read, w=write
    String line = f.readLine();
    String[] values = line.split(" ");
    int[] valueInt;
    for(int i = 1; i < values.length; i++) {
      valueInt[i-1] = Integer.pars(values[i]);
    }

or try the RandomaccesFile.readInt()-Methode

Upvotes: 1

djangofan
djangofan

Reputation: 29669

Use FileReader to read the file:

File tFile = loadGradleResource("testdata.int");
FileReader fileReader = null;
ArrayList<String> lines = new ArrayList<String>();
try {
    String line = null;
    fileReader = new FileReader( tFile );
    BufferedReader bufferedReader = new BufferedReader( fileReader );
    while ( !( line = bufferedReader.readLine() ).isEmpty() ) {
        lines.add(line); 
    }
    bufferedReader.close(); 
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
 }

And then this method to tokenize each line:

for ( String lin : lines ) {
    String[] stritems = lin.split( " " );
    for ( String it : stritems ) {
       // this shows how to parse to integer
       System.out.print( Integer.parseInt( it ) + "," );
    }
    System.out.println();
}

Upvotes: 0

erikd
erikd

Reputation: 11

Maybe something like this:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ReadNumbers {

    public List<int[]> getNumbers(InputStream is) throws IOException {
        List<int[]> result = new ArrayList<int[]>();
        BufferedReader reader = null;
        String line = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            while ((line = reader.readLine()) != null) {
                String[] s = line.split("\\s+");
                int[] numbers = new int[s.length - 1];
                for (int i = 0; i < numbers.length; i++) {
                    numbers[i] = Integer.parseInt(s[i + 1]);
                }
                result.add(numbers);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return result;
    }

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        ReadNumbers reader = new ReadNumbers();
        InputStream is = null;
        try {
            is = new FileInputStream("numbers.txt");
            List<int[]> numbers = reader.getNumbers(is);
            for (int[] n : numbers) {
                int sum = 0;
                for (int i : n) {
                    sum += i;
                }
                System.out.println("sum=" + sum);
            }
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignore) {
                }
            }
        }
    }
}

Upvotes: 1

Markus
Markus

Reputation: 2053

You can use the classes from the java.io and java.nio packages to. A BufferedReader can read line by line your file:

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new     File("Path"))));
String line = null;
while((line = br.readLine()) != null){
    //do stuff in here
}

In Google Guava there are helpful methods for reading a File.

The splitting of columns in this special case can be done by the split method of the String class.

line.split(" ");

For the splitting the usage of Google's Guava library might also be of big help for string splitting.

Handling of the numbers can be achieved by using the wrapper classes like Long, Integer and so on, especially the static methods valueOf in the respective classes.

Long.valueOf("123");

Upvotes: 2

Ravindra Gullapalli
Ravindra Gullapalli

Reputation: 9158

You can separate the first column like this.

import java.io.*;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("Path"))));
String line = null;
while((line = br.readLine()) != null){
    System.out.println(line.substring(line.indexOf(" ") + 1));
}
br.close();

Now you manipulate the rest of the string as required.

Upvotes: 2

Mojave Storm
Mojave Storm

Reputation: 571

I would use a double loop, one to split text in the file off the character '\n' which will give you a string array where each element is one line in the file, then iterate through that array and explode each row off the character ' '. From that point on it is just a matter of ignoring the first element in the resulting array.

Here's the function I'm talking about:

String.split

Upvotes: 1

Mike Adler
Mike Adler

Reputation: 1200

Use Google Guava's Files.readLines() method to get the Strings into a List. From there, parsing out the rest can be done either with a Regex or by simply counting letters. The Integer class comes with a parseInt(String) method that will transform the individual Strings into Integers.

Upvotes: 1

Related Questions