junaidp
junaidp

Reputation: 11201

How to read data from a text file and save some data from it to an Array

I have a text file in my computer which I am reading form my java program, I want to build some criteria. Here is my Notepad File :

   #Students
   #studentId   studentkey  yearLevel   studentName token   
   358314           432731243   12          Adrian      Afg56       
   358297           432730131   12          Armstrong   YUY89       
   358341           432737489   12          Atkins      JK671   

        #Teachers
        #teacherId  teacherkey    yearLevel teacherName token   
        358314          432731243   12          Adrian      N7ACD       
        358297          432730131   12          Armstrong   EY2C        
        358341          432737489   12          Atkins      F4NGH

when I read from this note pad file, I get the exact data as it is in my application but I want to read only the token column inside students and put them in my array named studentTokens. Here is the code

public static void main(String[] args) {
    ArrayList<String > studentTokens = new ArrayList<String>();

    try{
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new  FileInputStream("c:/work/data1.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());
    }
}

Upvotes: 1

Views: 36901

Answers (5)

PrimosK
PrimosK

Reputation: 13918

A short tip:

private static Integer STUDENT_ID_COLUMN = 0;
private static Integer STUDENT_KEY_COLUMN = 1;
private static Integer YEAR_LEVEL_COLUMN = 2;
private static Integer STUDENT_NAME_COLUMN = 3;
private static Integer TOKEN_COLUMN = 4;

public static void main(String[] args) {

    ArrayList<String> studentTokens = new ArrayList<>();

    try (FileInputStream fstream = new FileInputStream("test.txt");
          InputStreamReader inputStreamReader = new InputStreamReader(fstream);
          BufferedReader br = new BufferedReader(inputStreamReader)) {

        String strLine;

        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {

            strLine = strLine.trim();

            if ((strLine.length() != 0) && (strLine.charAt(0) != '#')) {
                String[] columns = strLine.split("\\s+");
                studentTokens.add(columns[TOKEN_COLUMN]);
            }

        }
    }
    catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
        return;
    }

    for (String s : studentTokens) {
        System.out.println(s);
    }
}

The above code is not complete solution. It extracts all tokens (for students and teachers). I hope you'll manage to make it work just for student tokens from there on...

Upvotes: 4

nIcE cOw
nIcE cOw

Reputation: 24616

Instead of doing things in java.io, you must think about shifting to java.nio, it has some very nice API now to work around with.

Here is a small code, that will give you the desired result.

import java.io.BufferedReader;

import java.nio.charset.Charset;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.util.ArrayList;
import java.util.List;

public class StudentToken
{
    public static void main(String[] args) throws Exception
    {       
        List<String> studenttoken = new ArrayList<String>();
        Path sourcePath = Paths.get(args[0]);
        Charset charset = Charset.forName("US-ASCII");
        BufferedReader reader = Files.newBufferedReader(sourcePath, charset);
        int width = 0;
        int height = 0;

        String line = null;     
        line = reader.readLine();
        while (!((line = reader.readLine()).trim()).equals("#Teachers"))
        {       
            line = line.trim();
            if (width == 0)
            {
                String[] str = line.split("\\s+");
                width = str.length;
            }           
            if (line.length() > 0)  
            height++;
        }
        reader.close();

        BufferedReader reader1 = Files.newBufferedReader(sourcePath, charset);
        reader1.readLine();
        for (int i = 0; i < height; i++)
        {
            if(!((line = reader1.readLine()).trim()).equals("#Teachers"))
            {
                line = line.trim();
                String[] str = line.split("\\s+");
                for (int j = 0; j < width; j++)
                {
                              // this condition will add only those elements which fall under token column.
                    if (j == (height) && i != 0) 
                        studenttoken.add(str[j]);                   
                }
            }
        }
        reader1.close();
        System.out.println(studenttoken);
    }
}

Here is the output of the test run :

enter image description here

Hopefully that might help. Regards.

Upvotes: 1

Raveesh Sharma
Raveesh Sharma

Reputation: 1486

You are simple printing the line . I believe there are can be two ways Since your token element is the fifth element, you can split the string and utilize the 5th element directly

String splitString = strLine.split("\t"); String tokenvalue = splitString[4];

Or maintain as a csv file for easy manipulation

Upvotes: 0

dogbane
dogbane

Reputation: 274522

Take a look at the String.split method, which will help you split each line on space. Once you have split it, you can retrieve the value of the token column. Finally, call ArrayList.add to add it to your list.

Upvotes: 0

Rostislav Matl
Rostislav Matl

Reputation: 4543

You can read the file line by line and use String.split("\s+").

Upvotes: 0

Related Questions