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

7
我知道如何使用Java的Scanner和File IOException读取文件,但我不知道如何将文件中的文本存储为数组。
以下是我的代码片段:
 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();

这是我的 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   
7个回答

16

存储为字符串:

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

对于浮点数:

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

new LinkedList<String>(); 在这种情况下使用链表的理由是什么? - njzk2
@njzk2 嗯,我不认为有一个好的理由。ArrayList可能更可取,除非要向列表中添加未知数量的温度。我更新了我的答案。 - rainkinz
我认为一个好的例子也应该关闭inFile1扫描器(因此关闭输入文件)。虽然在main中只做这个可能没关系,但在更大的应用程序中可能会成为一个问题。 - SergGr

2

只需将整个文件读入StringBuilder,然后按空格后的点号分割String。您将得到一个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(", ");

请您能否详细解释一下您的意思,我对Java编程还比较新。 - word word
编辑并添加了示例。 - Utku Özdemir

2
如果您不知道文件中的行数,就没有大小可以用来初始化一个数组。在这种情况下,使用List更有意义:
List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
    tokens.add(inFile1.nextLine());
}

接下来,如果需要,您可以将其复制到数组中:

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

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

}

0

我发现从文件中读取字符串的这种方式对我来说效果最好

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

"full"将是所有行的组合完成形式。如果您想在文本行之间添加换行符,可以这样做:full+=st+"\n";


这在100kb-1mb范围内的小文件上都非常缓慢。您可以在此处查看一些统计信息https://dev59.com/A1PTa4cB1Zd3GeqPnu5g#17757230,使用StringBuilder代替! - kritzikratzi

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

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

编辑

看起来你想创建一个浮点数数组,为此创建一个浮点数数组即可。

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

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

那么你的浮点数数组将会是这样的

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

当文件中的行数超过200行时,程序会立即崩溃。顺便问一下,前置自增是怎么回事?计数器将包含读取行数减1的结果... - njzk2
是的,200只是一个假设值,我通常会将内容存储在一个单一的数组中。是的,计数器会存储读取的行数。 - Ankit Rustagi
在你的情况下,计数器为0当读取了1行时。我通常会将内容存储在一个单一的数组中。我不理解那部分。 - njzk2
那很明显,我会计数,这样如果将来需要在for循环中使用它会有所帮助。 - Ankit Rustagi

0

我使用这个方法:

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

为什么要使用Scanner以预分割的方式读取文件,然后再将它们连接并再次拆分?为什么要在三年前的问题中添加这样的答案,而没有任何新的好主意呢? 请注意,您的代码中还有其他“坏味道”。为什么scn是静态成员而不是局部变量?如果出现FileNotFoundException会发生什么?(提示:NullPointerException)。如果此片段将用于更大的应用程序,则不关闭扫描器也不是一个好主意。 - SergGr
在项目结构中,您应该把'test.txt'放在哪里才能仅通过名称找到它,看起来您没有使用路径? - Androidcoder
在项目结构中,你要把'test.txt'放在哪里才能通过文件名找到它,看起来你没有使用路径? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接