在java中,我如何从文件中读取数据并创建数组集合?

时间:2020-12-18 12:55:46

I am trying to run Junit Parameterized test. Following is how Junit suggests to add data to collection of arrays.

我正在尝试运行Junit参数化测试。以下是Junit建议如何将数据添加到数组集合中。

Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };  
return Arrays.asList(data);  

This however requires user to add the data in the code. I want to read data from file (about 300 lines) and convert it into collection of Arrays. How can I do that ?

但是,这要求用户在代码中添加数据。我想从文件中读取数据(大约300行)并将其转换为数组集合。我怎样才能做到这一点 ?

Here is the code:

这是代码:

import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;



@RunWith(value=Parameterized.class)
public class UrlParameterizedTest {

    private String url;
    public static ArrayList<String>dataArray=new ArrayList<String>();
    static File directory = new File(".");
    public static String fileToRead;

    public UrlParameterizedTest(String url){
        this.url=url;
    }
    @Parameters
    public static Collection<Object[]> data() throws Exception {

        try {
            fileToRead=directory.getCanonicalPath()+"\\Data\\LinkChecker.csv";
            loadDataFile(fileToRead);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    Object[][]data=new Object[dataArray.size()][];
      *******   //convert dataArray to data here.************
        return Arrays.asList(data);

    }

    @Test
    public void testURLs() {
        System.out.println("Parameterized Number is "+url);
    }

    public static void loadDataFile(String dataFile) throws Exception {
        dataArray.clear();
        //if data_file is absolute, use this
        try
        {
            // Open an input stream
            // Read a line of text
            String line="";
            BufferedReader br=new BufferedReader(new FileReader(dataFile));
            while((line=br.readLine())!=null) {
                dataArray.add(line);
            }
            br.close();
            System.out.println("The data file length is "+ dataArray.size());
        }

        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println ("Unable to read from file");
        }
    }
}

3 个解决方案

#1


2  

Use Apache Commons FileUtils.readFileToString to read the file to a string. Then you will need to parse the file into the collection of arrays. We cannot help you on how to parse the file and we don't know the contents.

使用Apache Commons FileUtils.readFileToString将文件读取为字符串。然后,您需要将文件解析为数组集合。我们无法帮助您解析如何解析文件,我们不知道内容。

FileUtils.readFileToString

#2


0  

In order to retrieve strings from a File you could use something like the follow code; then you could retrieve data from your ArrayList and put them in your array (using "toArray()" method provided by Class ArrayList).

为了从文件中检索字符串,您可以使用类似以下代码的内容;然后你可以从ArrayList中检索数据并将它们放入你的数组中(使用Class ArrayList提供的“toArray()”方法)。

ArrayList<String> strings=new ArrayList<String >();
String filePath = path + "/" + fileName;

FileInputStream fin = null;
            try {
                fin = new FileInputStream(filePath);
            } catch (IOException e) {
                System.out.println (e.toString()); 
                System.out.println("File " + fileName + " not found.");
            }

            DataInputStream in = new DataInputStream(fin);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine = null;


            while ((strLine = br.readLine()) != null)   {

                strings.add(strLine);
            }

            in.close();

#3


0  

Put your data in a file, one under the other. Use a scanner to read them as strings and then convert them to numbers (I assumed that they should be float numbers). Something like this:

将您的数据放在一个文件中,一个放在另一个文件中。使用扫描仪将它们作为字符串读取,然后将它们转换为数字(我假设它们应该是浮点数)。像这样的东西:

ArrayList<Float> numbers = new ArrayList<Float>();
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
    String nextLine = scanner.nextLine();
    float value = Float.parseFloat(nextLine);
    numbers.add(value);
}
scanner.close();

#1


2  

Use Apache Commons FileUtils.readFileToString to read the file to a string. Then you will need to parse the file into the collection of arrays. We cannot help you on how to parse the file and we don't know the contents.

使用Apache Commons FileUtils.readFileToString将文件读取为字符串。然后,您需要将文件解析为数组集合。我们无法帮助您解析如何解析文件,我们不知道内容。

FileUtils.readFileToString

#2


0  

In order to retrieve strings from a File you could use something like the follow code; then you could retrieve data from your ArrayList and put them in your array (using "toArray()" method provided by Class ArrayList).

为了从文件中检索字符串,您可以使用类似以下代码的内容;然后你可以从ArrayList中检索数据并将它们放入你的数组中(使用Class ArrayList提供的“toArray()”方法)。

ArrayList<String> strings=new ArrayList<String >();
String filePath = path + "/" + fileName;

FileInputStream fin = null;
            try {
                fin = new FileInputStream(filePath);
            } catch (IOException e) {
                System.out.println (e.toString()); 
                System.out.println("File " + fileName + " not found.");
            }

            DataInputStream in = new DataInputStream(fin);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine = null;


            while ((strLine = br.readLine()) != null)   {

                strings.add(strLine);
            }

            in.close();

#3


0  

Put your data in a file, one under the other. Use a scanner to read them as strings and then convert them to numbers (I assumed that they should be float numbers). Something like this:

将您的数据放在一个文件中,一个放在另一个文件中。使用扫描仪将它们作为字符串读取,然后将它们转换为数字(我假设它们应该是浮点数)。像这样的东西:

ArrayList<Float> numbers = new ArrayList<Float>();
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
    String nextLine = scanner.nextLine();
    float value = Float.parseFloat(nextLine);
    numbers.add(value);
}
scanner.close();