Java读取文件并将文本存储在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19844649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:38:55  来源:igfitidea点击:

Java read file and store text in an array

javaarraysfile-iostoring-data

提问by word word

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

我知道如何Java使用 usingScanner和 File IOException读取文件,但我唯一不知道的是如何将文件中的文本作为数组存储。

Here is a snippetof my code:

这是snippet我的代码:

 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.txtfile contains:

这是我的KeyWestTemp.txt文件包含的内容:

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

采纳答案by rainkinz

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

回答by Ankit Rustagi

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

回答by Paul Samsotha

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

}

回答by Utku ?zdemir

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

只需将整个文件读入 StringBuilder,然后在空格后按点分割字符串。你会得到一个字符串数组。

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

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

String[] yourArray = sb.toString().split(", ");

回答by njzk2

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 更有意义:

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

回答by Elipzer

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

“full”将是所有行的完整组合。如果你想在文本行之间添加一个换行符,你会这样做 full+=st+"\n";

回答by Ayakashi

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