Java read file and store text in an array
Asked Answered
P

7

7

I know how to read a file with Java using Scanner and File IOException, but the only thing I don't know is how to store the text in the files as an array.

Here is a snippet of my code:

 public static void main(String[] args) throws IOException{
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1
    String token1 = "";

    // for-each loop for calculating heat index of May - October


    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));

    // while loop
    while(inFile1.hasNext()){

        // how can I create array from text read?

        // find next line
        token1 = inFile1.nextLine();

Here is what my KeyWestTemp.txt file contains:

70.3,   70.8,   73.8,   77.0,   80.7,   83.4,   84.5,   84.4,   83.4,   80.2,   76.3,   72.0   
Phenformin answered 7/11, 2013 at 19:14 Comment(0)
G
16

Stored as strings:

public class ReadTemps {

    public static void main(String[] args) throws IOException {
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1
    String token1 = "";

    // for-each loop for calculating heat index of May - October

    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");

    // Original answer used LinkedList, but probably preferable to use ArrayList in most cases
    // List<String> temps = new LinkedList<String>();
    List<String> temps = new ArrayList<String>();

    // while loop
    while (inFile1.hasNext()) {
      // find next line
      token1 = inFile1.next();
      temps.add(token1);
    }
    inFile1.close();

    String[] tempsArray = temps.toArray(new String[0]);

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

For floats:

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class ReadTemps {

  public static void main(String[] args) throws IOException {
    // TODO code application logic here

    // // read KeyWestTemp.txt

    // create token1

    // for-each loop for calculating heat index of May - October

    // create Scanner inFile1
    Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");


    // Original answer used LinkedList, but probably preferable to use ArrayList in most cases
    // List<Float> temps = new LinkedList<Float>();
    List<Float> temps = new ArrayList<Float>();

    // while loop
    while (inFile1.hasNext()) {
      // find next line
      float token1 = inFile1.nextFloat();
      temps.add(token1);
    }
    inFile1.close();

    Float[] tempsArray = temps.toArray(new Float[0]);

    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }
}
Grania answered 7/11, 2013 at 19:30 Comment(3)
new LinkedList<String>(); what justifies the use of a linkedlist in this case?Incurrent
@Incurrent Hmm, I don't think there is a good reason for it. ArrayList would probably be preferable unless there were a unknown large number of temperatures being added to the list. Updated my answer.Grania
I think that good example should also close the inFile1 Scanner (and thus the input file). It doesn't matter if this is all you do in main but in a bigger applicaiton it might become an issue.Weiser
J
2

Just read the whole file into a StringBuilder, then split the String by dot following a space. You will get a String array.

Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));

StringBuilder sb = new StringBuilder();
while(inFile1.hasNext()) {
    sb.append(inFile1.nextLine());
}

String[] yourArray = sb.toString().split(", ");
Jalap answered 7/11, 2013 at 19:20 Comment(2)
May you please explain to me more in detail on what you mean by this, I am fairly new to Java programming.Phenformin
Edited and added example.Pockmark
I
2

If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :

List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
    tokens.add(inFile1.nextLine());
}

After that, if you need to, you can copy to an array :

String[] tokenArray = tokens.toArray(new String[0]);
Incurrent answered 7/11, 2013 at 19:21 Comment(0)
M
1
while(inFile1.hasNext()){

    token1 = inFile1.nextLine();

    // put each value into an array with String#split();
    String[] numStrings = line.split(", ");

    // parse number string into doubles 
    double[] nums = new double[numString.length];

    for (int i = 0; i < nums.length; i++){
        nums[i] = Double.parseDouble(numStrings[i]);
    }

}
Mercantilism answered 7/11, 2013 at 19:19 Comment(0)
O
0
int count = -1;
String[] content = new String[200];
while(inFile1.hasNext()){

    content[++count] = inFile1.nextLine();
}

EDIT

Looks like you want to create a float array, for that create a float array

int count = -1;
Float[] content = new Float[200];
while(inFile1.hasNext()){

    content[++count] = Float.parseFloat(inFile1.nextLine());
}

then your float array would look like

content[0] = 70.3
content[1] = 70.8
content[2] = 73.8
content[3] = 77.0 and so on
Oldtimer answered 7/11, 2013 at 19:16 Comment(4)
crashes as soon as there are more than 200 lines in the file. what's with the preincrementation anyway ? count will contain the number of read lines - 1 ....Incurrent
Yes 200 was an assumption, i would usually store the content in one single array. Yes count would store the number of lines read.Oldtimer
in your case, no, count is 0 when 1 line was read. i would usually store the content in one single array. i didn't understand that part.Incurrent
That would be pretty obvious, i keep count so that it would help in for loops in future if the need be.Oldtimer
H
0

I have found this way of reading strings from files to work best for me

String st, full;
full="";
BufferedReader br = new BufferedReader(new FileReader(URL));
while ((st=br.readLine())!=null) {
    full+=st;
}

"full" will be the completed combination of all of the lines. If you want to add a line break between the lines of text you would do full+=st+"\n";

Hardball answered 7/11, 2013 at 19:29 Comment(1)
this is incredibly slow even on small files in the 100kb-1mb range. you can see some stats here https://mcmap.net/q/1128028/-how-to-read-a-text-file-from-quot-assets-quot-directory-as-a-string use a stringbuilder instead!Nikko
H
0

I use this method:

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

public class TEST {
    static Scanner scn;

public static void main(String[] args) {
    String text = "";

    try{
        scn = new Scanner(new File("test.txt"));
    }catch(FileNotFoundException ex){System.out.println(ex.getMessage());}
    while(scn.hasNext()){
        text += scn.next();
        }
        String[] arry = text.split(",");

    //if need converting to float do this:
    Float[] arrdy = new Float[arry.length];
    for(int i = 0; i < arry.length; i++){
            arrdy[i] = Float.parseFloat(arry[i]);
        }
    System.out.println(Arrays.toString(arrdy));
            }
}
Hike answered 1/3, 2017 at 22:1 Comment(2)
Why do you use Scanner to read file in a pre-splitted way just to join parts and split them again? What's the reason to add such answer to 3-years old question without any new good ideas? Please also note that there are other "bad smells" in your code. Why scn is a static member instead of just local variable? What happens if there was FileNotFoundException? (Hint: NullPointerException). Not closing Scanner is also not a good idea if this snippet would be used in a bigger application.Weiser
where do you put 'test.txt' in the project structure to be found by just the name, looks like your not using a path?Herbivorous

© 2022 - 2024 — McMap. All rights reserved.