这是我的第一篇文章,如果我搞砸了或者我不够清楚,我深表歉意。我已经在网上论坛上浏览了几个小时,并花了更多时间自己弄明白。
我正在从一个文件中读取信息,我需要一个循环来创建一个 ArrayList。
static ArrayList<String> fileToArrayList(String infoFromFile)
{
ArrayList<String> smallerArray = new ArrayList<String>();
//This ArrayList needs to be different every time so that I can add them
//all to the same ArrayList
if (infoFromFile != null)
{
String[] splitData = infoFromFile.split(":");
for (int i = 0; i < splitData.length; i++)
{
if (!(splitData[i] == null) || !(splitData[i].length() == 0))
{
smallerArray.add(splitData[i].trim());
}
}
}
我需要这样做的原因是我正在为学校项目创建一个应用程序,该应用程序从带分隔符的文本文件中读取问题。我之前有一个循环,一次从文本中读取一行。我将把那个字符串插入到这个程序中。
每次通过此方法时,如何使 ArrayList smallerArray 成为一个单独的 ArrayList?
我需要这个,这样我就可以拥有每个 ArrayList 的 ArrayList
最佳答案
这是您打算执行的操作的示例代码 -
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class SimpleFileReader {
private static final String DELEMETER = ":";
private String filename = null;
public SimpleFileReader() {
super();
}
public SimpleFileReader(String filename) {
super();
setFilename(filename);
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public List<List<String>> getRowSet() throws IOException {
List<List<String>> rows = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(row -> rows.add(Arrays.asList(row.split(DELEMETER))));
}
return rows;
}
}
并且,这是对上述代码的 JUnit 测试 -
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.Test;
public class SimpleFileReaderTest {
public SimpleFileReaderTest() {
super();
}
@Test
public void testFileReader() {
try {
SimpleFileReader reader = new SimpleFileReader("c:/temp/sample-input.txt");
List<List<String>> rows = reader.getRowSet();
int expectedValue = 3; // number of actual lines in the sample file
int actualValue = rows.size(); // number of rows in the list
if (actualValue != expectedValue) {
fail(String.format("Expected value for the row count is %d, whereas obtained value is %d", expectedValue, actualValue));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
关于java - 在 Java 的 Arraylist 中创建 Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55244618/