简体   繁体   English

从文本文件将数据加载到数组中

[英]Loading data into an array from a text file

I'm really struggling with a piece of work, I need to load data from a text file into an array, I have managed to load the data into java and print it, but now the data needs to be split and passed to another class. 我真的很努力工作,我需要将数据从文本文件加载到数组中,我设法将数据加载到java中并打印出来,但是现在需要拆分数据并将其传递给另一个类。 I tried using .split(" ") but the data doesn't share a common amount of white space so I end up with a huge array half of which is filled with entries that have 2 lots of data or just a white space. 我尝试使用.split(" ")但数据共享的空白空间不大,因此我最终得到一个巨大的数组,其中一半充满了具有2个大量数据或仅有空白的条目。 Here is the code I have so far: 这是我到目前为止的代码:

import java.io.*;

public class Reader {

    int i= 0;
    int k=0;
    static String test;

    public static void main(String[] Args){ 

    String file ="1RainfallSample.txt";        

    //reading   
    try{
        InputStream ips=new FileInputStream(file); 
        InputStreamReader ipsr=new InputStreamReader(ips);
        BufferedReader br=new BufferedReader(ipsr);
        String line;
        while ((line=br.readLine())!=null){
        test+=line+"\n";
        }
        br.close(); 

    }       
    catch (Exception e){
        System.out.println(e.toString());
    } 

    // split(String Delimiter)
    String[] dataArray=test.split("\\s");
    System.out.println("Array :"+dataArray.length);
    for(int i=0;i<dataArray.length;i++)
    {
        System.out.println("array"+i+"  :"+dataArray[i]);
    } 

    }
}

And below is a small example of the data because I don't think I explained it very well. 下面是数据的一个小示例,因为我认为我没有很好地解释它。

4   6.10   1.80   1.00  26.10   9.60   0.00   0.00   0.00 

0.00   0.00   3.10   0.30   0.20   0.40  0.00   0.00   0.00   0.00   0.00   0.00   

0.00   2.50   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00 -99.992011

I feel like I'm approaching it all the wrong way, I'm not a good programmer as you can tell, just a nudge in the right direction would be appreciated. 我觉得我正在以错误的方式处理问题,正如您所知,我不是一个优秀的程序员,只是朝着正确的方向前进。

You can use 您可以使用

String[] dataArray = test.split("\\s+");

to get rid of extra white spaces. 摆脱多余的空白。

Alternatively if you want to tidy your data, you could match duplicate spaces and remove them or replace with a single space. 或者,如果您要整理数据,则可以匹配重复的空格并将其删除或替换为单个空格。

First make sure your text is in a string variable, then: 首先确保您的文本在字符串变量中,然后:

Val = Val.replaceAll(" {2,}", " ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM