[java] Java read file and store text in an array

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   

This question is related to java arrays file-io storing-data

The answer is


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);
    }
  }
}

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));
            }
}

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(", ");

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

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";


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]);
    }

}

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]);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to storing-data

Java read file and store text in an array