假设有一个名为SUN.txt的文件
文件内容:a,b,dd,ss,
我想根据文件中属性数量创建动态数组。如果逗号后面是字符,则数组长度为0-4,即长度为5。在上述情况下,没有字符返回0-3长度为4的数组。我也想读取逗号后面的NULL。
我该如何做?
Sundhas
文件内容:a,b,dd,ss,
我想根据文件中属性数量创建动态数组。如果逗号后面是字符,则数组长度为0-4,即长度为5。在上述情况下,没有字符返回0-3长度为4的数组。我也想读取逗号后面的NULL。
我该如何做?
Sundhas
你应该考虑
String.split(",")
,你可能会发现需要将-1
传递给限制参数,就像这样String.split(",", -1)
,以便获取最后一个元素为空字符串的情况。请参考我发布的答案。 - Camilo Díaz Repka//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//The StringBuffer will be used to create a string if your file has multiple lines
StringBuffer sb = new StringBuffer();
String line;
while((line = reader.readLine())!= null)
{
sb.append(line);
}
//We now split the line on the "," to get a string array of the values
String [] store = sb.toString().split(",");
我不太理解为什么您想在逗号后面添加NULL?我假设您是指在数组的最后一个逗号后面添加NULL?我不太明白这样做的意义,但这不是问题所在。
如果是这种情况,您不会读取到NULL,如果逗号后面有空格,您可以读取它。
如果您需要NULL,则需要自己在末尾添加。您可以做如下操作:
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//Use an arraylist to store the values including nulls
ArrayList<String> store = new ArrayList<String>();
String line;
while((line = reader.readLine())!= null)
{
String [] splitLine = line.split(",");
for(String x : splitLine)
{
store.add(line);
}
//This tests to see if the last character of the line is , and will add a null into the array list
if(line.endsWith(","))
store.add(null);
}
String [] storeWithNull = store.toArray();
如果你想简单地打开文件并将内容存储在字符串数组中,那么:
1)将文件打开为字符串
2)使用正则表达式“,”分割字符串http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split(java.lang.String
但我很好奇,为什么你不能直接使用一个字符串文件呢?
使用BufferedReader
逐行读取文件。
使用split(",", -1)
将其转换为包括最后一个逗号之后的空字符串在内的String[]
数组。
将String[]
部分加载到List
中。
对于你的数据结构,使用一个数组列表。每个列表条目都是文本文件中的一行,每个条目都是包含逗号分隔值的数组:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
data.add(line.split(","));
line = readNextLine();
}
(假设您的文件包含1..n行逗号分隔值)
"a,b,c,d," -> {"a", "b", "c", "d", null}
这里有一个解决该问题的建议:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
String[] values = new String[5];
String[] pieces = line.split(",");
for (int i = 0; i<pieces.length; i++)
values[i] = pieces[i];
data.add(values);
line = readNextLine();
}
看起来像是 CSV 文件,假设有 5 行和 5 个值,类似这样的东西会起作用
String [][] value = new String [5][5];
File file = new File("SUN.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
int row = 0;
int col = 0;
while((line = br.readLine()) != null ){
StringTokenizer s = new StringTokenizer(line,",");
while (s.hasMoreTokens()){
value[row][col] = s.nextToken();
col++;
}
col = 0;
row++;
}
我还没有测试过这段代码