Java leest bestand en slaat tekst op in een array

Ik weet hoe ik een bestand moet lezen met Java met behulp van Scanner en File IOException, maar het enige dat ik niet weet, is hoe ik de tekst in de bestanden moet opslaan als een array.

Hier is een snippet van mijn 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();

Dit is wat mijn KeyWestTemp.txt-bestand bevat:

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

Antwoord 1, autoriteit 100%

Opgeslagen als tekenreeksen:

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

Voor drijvers:

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

Antwoord 2, autoriteit 13%

Als je het aantal regels in je bestand niet weet, heb je geen grootte waarmee je een array moet initiëren. In dit geval is het logischer om een ​​lijst te gebruiken:

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

Daarna kunt u, indien nodig, naar een array kopiëren:

String[] tokenArray = tokens.toArray(new String[0]);

Antwoord 3, autoriteit 13%

Lees gewoon het hele bestand in een StringBuilder en splits de String vervolgens per punt na een spatie. Je krijgt een 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(", ");

Antwoord 4, autoriteit 7%

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

Antwoord 5

int count = -1;
String[] content = new String[200];
while(inFile1.hasNext()){
    content[++count] = inFile1.nextLine();
}

BEWERKEN

Het lijkt erop dat je een float-array wilt maken, maak daarvoor een float-array

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

dan zou je float-array er zo uitzien

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

Antwoord 6

Ik heb ontdekt dat deze manier om strings uit bestanden te lezen het beste voor mij werkt

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

“full” is de voltooide combinatie van alle regels. Als u een regeleinde tussen de regels tekst wilt toevoegen, doet u dat:
full+=st+"\n";


Antwoord 7

Ik gebruik deze methode:

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

seventeen − fourteen =

Other episodes