需要将一组文本字符串文件读入2D数组。文本字符串格式如下所示,每行以“\ n”结尾,各种长度
"dog", "runs", "fast"
"birds", "flies", "high"
"baby", "cries", "often", "in the evening"
"He", "works"
....
想获得下面的2D数组输出:
{ {"dog", "runs", "fast"}, {"birds", "flies", "high"},
{"baby", "cries", "often", "in the evening"}, {"He", "works"},
...
}
考虑使用StringBuilder从文件中读取每一行并将其附加到2D Object [] []数组(但使用String [] []代替)。以下代码是我最初的尝试 - 不是很好,但也不起作用。
import java.io.*;
import java.util.*;
public class My2DArrayTest
{
public static void main(String args[])
{
String[][] myString = new String[4][3];
try
{
FileReader file = new FileReader("MyTestFile.txt");
BufferedReader reader = new BufferedReader (file);
String strLine;
String EXAMPLE_TEST;
for (int row = 0; row < 4; row++) {
for (int column = 0; column < 3; column++) {
while ((strLine = reader.readLine()) != null{
if (strLine.length() > 0) {
EXAMPLE_TEST = strLine;
System.out.println ("This is EXAMPLE_TEST: " +
EXAMPLE_TEST);
myString[row][column]=EXAMPLE_TEST;
System.out.println("Current row: " + row);
System.out.println("Current column: " + column);
System.out.println("This is myString Array:" +
myString[row][column] + " ");
}
}
}
}
file.close();
} catch( IOException ioException ) {}
}
}
答案 0 :(得分:1)
只需在char []中一次读取整个文件,然后将其转换为字符串。将字符串拆分为&#34; \ n&#34;得到一条线,然后再分开线&#34;,&#34;。我认为这将有魅力。
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Fileto2darray {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("yourfilename.txt");
FileReader fr = new FileReader(file);
char temparr[] = new char[(int) file.length()];
fr.read(temparr,0,(int) file.length());
String [] tempstring = (new String(temparr)).split("\n");
String array2d[][] = new String [tempstring.length][];
for(int i=0 ; i<tempstring.length; i++)
{
array2d[i]=tempstring[i].split(", ");
}
}
}
答案 1 :(得分:0)
利用Guava Tables:
public static void main(final String... args) throws Exception {
final String myString = "\"a\",\"b\",\"c\"\n" + "\"d\",\"e\",\"f\"\n";
final File tempFile = File.createTempFile("myTempFile", ".txt");
Files.append(myString, tempFile, Charset.defaultCharset());
final List<String> stringsFromFile = Files.readLines(tempFile, Charset.defaultCharset());
final Table<Integer, Integer, String> hashBasedTable = HashBasedTable.create();
for (int row = 0; row < stringsFromFile.size(); row++) {
final List<String> strings = Splitter.on(",")
.splitToList(stringsFromFile.get(row));
for (int column = 0; column < strings.size(); column++) {
hashBasedTable.put(row, column, strings.get(column));
}
}
final String[][] stringArrayArray = ArrayTable.create(hashBasedTable)
.toArray(String.class);
// "a""b""c"
// "d""e""f"
for (int i = 0; i < stringArrayArray.length; i++) {
final String[] row = stringArrayArray[i];
for (int j = 0; j < row.length; j++) {
System.out.print(row[j]);
}
System.out.println("");
}
}
答案 2 :(得分:0)
假设每个字符后面都有一个空格("a", "b", "c"
而不是"a","b","c"
),那么应该这样做。
我正在使用Scanner
读取输入的每一行,然后逐字处理(使用默认分隔符)。然后对于每个单词,我将第二个char("
之后的char添加到大小为3的char数组。然后我将此数组添加到2d数组。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CharArray {
char[][] charArray = new char[100][3];
int numOfElements = 0;
private void testOutput(){
for(int i = 0; i < numOfElements; i++){
for(char c : charArray[i])
System.out.print(c);
System.out.println();
}
}
private char[] processLine(Scanner lineScanner){
char[] result = new char[3];
for(int i = 0; i < 3; i++){
result[i] = lineScanner.next().charAt(1);
}
return result;
}
private void convertToArray(){
Scanner in = null;
try {
in = new Scanner(new FileInputStream("charsInput.txt"));//use w/e source for input
} catch (FileNotFoundException e) {
System.exit(0);
e.printStackTrace();
}
while(in.hasNextLine()){
charArray[numOfElements] = processLine(new Scanner(in.nextLine()));
numOfElements++;
}
testOutput();
}
public static void main(String[] args){
new CharArray().convertToArray();
}
}
唯一的问题是我的2d数组的大小为100.如果您不知道输入的行数,您可以读取输入一次以计算它有多少行然后再次读取它来处理它
例如类似的东西:
charArray = new char[countLines()][3];
private int countLines(){
Scanner in = null;
int counter = 0;
try {
in = new Scanner(new FileInputStream("charsInput.txt"));//use w/e source for input
} catch (FileNotFoundException e) {
System.exit(0);
e.printStackTrace();
}
while(in.hasNextLine())
counter ++;
return counter;
}
之后执行我之前提到的解析输入。希望他的帮助。
答案 3 :(得分:0)
这看起来像正则表达式的工作!我相信大多数文件/行解析应该用REGEX完成。
^\s*(\"[a-z]\"),\s*(\"[a-z]\"),\s*(\"[a-z]\")\s*$
修改强>
我没有意识到你想要的只是三个输入。我更新了以反映这些启示。
\s*(\"[a-z]+\")(?:,\s*|\s*$)
想法:
当您逐行读取文件时,您将检索String
数组非常简单。
该数组将包含3个索引,这些索引将与我的图表中标记的捕获组相关联。您获得的字符串数组应该加载到list
。然后,如果您选择2D阵列,则可以卸载它。
String[] s = {group1, group2, group3};
List<String[]> arrayList = new ArrayList<String[]>();
arrayList.add(s);
注意: 如果您需要一个关于如何实现REGEX(正则表达式)以及如何从捕获组中解析它们的示例,请告诉我。
答案 4 :(得分:0)
首先,您必须决定如何处理您在开始时不知道行数的事实。你可以:
List
内。(我将选择2)其次,你想在字符串中允许哪些字符?例如"
或\n
(换行符)可能会使事情变得更复杂,因为您必须将它们转义,但我们假设这些字符将被禁止(以及,
,所以我们可以更轻松地拆分)
Scanner in = new Scanner(new File("strings.test"));
List<String[]> lines = new ArrayList<>();
while(in.hasNextLine()) {
String line = in.nextLine().trim();
String[] splitted = line.split(", ");
for(int i = 0; i<splitted.length; i++) {
//get rid of additional " at start and end
splitted[i] = splitted[i].substring(1, splitted[i].length()-1);
}
lines.add(splitted);
}
//pretty much done, now convert List<String[]> to String[][]
String[][] result = new String[lines.size()][];
for(int i = 0; i<result.length; i++) {
result[i] = lines.get(i);
}
System.out.println(Arrays.deepToString(result));
输出:
[[dog, runs, fast], [birds, flies, high], [baby, cries, often, in the evening], [He, works]]
如果你需要任何我被甩掉的人,请在评论中告诉我,我会编辑这个答案。