web-dev-qa-db-fra.com

Java lire le fichier et stocker le texte dans un tableau

Je sais lire un fichier avec Java en utilisant Scanner et File IOException, mais la seule chose que je ne sais pas, c'est comment stocker le texte dans les fichiers sous forme de tableau.

Voici un snippet de mon 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();

Voici ce que mon KeyWestTemp.txt le fichier contient:

70.3,   70.8,   73.8,   77.0,   80.7,   83.4,   84.5,   84.4,   83.4,   80.2,   76.3,   72.0   
7
word word

Stocké sous forme de chaînes:

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

Pour les flotteurs:

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

Si vous ne connaissez pas le nombre de lignes de votre fichier, vous n'avez pas de taille avec laquelle initier un tableau. Dans ce cas, il est plus logique d'utiliser une liste:

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

Après cela, si vous en avez besoin, vous pouvez copier dans un tableau:

String[] tokenArray = tokens.toArray(new String[0]);
2
njzk2
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]);
    }

}
1
Paul Samsotha

J'ai trouvé que cette façon de lire les chaînes de fichiers fonctionnait le mieux pour moi

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

"full" sera la combinaison complète de toutes les lignes. Si vous souhaitez ajouter un saut de ligne entre les lignes de texte, vous feriez full+=st+"\n";

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

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

MODIFIER

On dirait que vous voulez créer un tableau flottant, pour cela créer un tableau flottant

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

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

alors votre tableau flottant ressemblerait

content[0] = 70.3
content[1] = 70.8
content[2] = 73.8
content[3] = 77.0 and so on
0
Ankit Rustagi

Il suffit de lire le fichier entier dans un StringBuilder, puis de diviser la chaîne par point en suivant un espace. Vous obtiendrez un tableau String.

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

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

String[] yourArray = sb.toString().split(", ");
0
Utku Özdemir