java读取txt并存储到二维数组中出现有关问题
java读取txt并存储到二维数组中出现问题
最近开始研究java,在学习过程中遇到了一些问题,请求帮助。
我要把一个txt文档中的数据按行读取出来,并且每一行都是由逗号加空格分隔开,现在想把这些词储存到一个二维数组中,自己写了一个程序老是会报错,跪求大神帮忙看看,感激不尽。

这个是txt存储的格式,下面是代码:
public static void main(String[] args)throws Exception {
File fp=new File("C:\\Users\\yang fan\\workspace\\welcome java\\3.txt");
FileReader newreader = new FileReader(fp);
int newfileLen = (int)fp.length();
char[] newchars = new char[newfileLen];
newreader.read(newchars);
String newcontent = String.valueOf(newchars);
String[] newlist = newcontent.split("\\r");
int x = newlist.length;
String[][] data=new String[x][15];
int i=0;
while (i<x-1){
String[] word = newlist[i].split(", ");
for(int k=0;k<15;k++){
data[i][k]=word[k];
}
i++;
}
for ( i=0;i<x-1;i++){
for(int k=0;k<15;k++){
System.out.println(data[i][k]);
}
}
newreader.close();
}
------解决思路----------------------
不知道22行是哪里? 可能是这里:
你试试这个
------解决思路----------------------
读文件内容,转成String[][]
输入String[][]
最近开始研究java,在学习过程中遇到了一些问题,请求帮助。
我要把一个txt文档中的数据按行读取出来,并且每一行都是由逗号加空格分隔开,现在想把这些词储存到一个二维数组中,自己写了一个程序老是会报错,跪求大神帮忙看看,感激不尽。
这个是txt存储的格式,下面是代码:
public static void main(String[] args)throws Exception {
File fp=new File("C:\\Users\\yang fan\\workspace\\welcome java\\3.txt");
FileReader newreader = new FileReader(fp);
int newfileLen = (int)fp.length();
char[] newchars = new char[newfileLen];
newreader.read(newchars);
String newcontent = String.valueOf(newchars);
String[] newlist = newcontent.split("\\r");
int x = newlist.length;
String[][] data=new String[x][15];
int i=0;
while (i<x-1){
String[] word = newlist[i].split(", ");
for(int k=0;k<15;k++){
data[i][k]=word[k];
}
i++;
}
for ( i=0;i<x-1;i++){
for(int k=0;k<15;k++){
System.out.println(data[i][k]);
}
}
newreader.close();
}
------解决思路----------------------
不知道22行是哪里? 可能是这里:
int i=0;
while (i<x-1){
String[] word = newlist[i].split(", ");
for(int k=0;k<15;k++){
data[i][k]=word[k];
}
i++;
}
你试试这个
while( i < data.length ){
String[] word = newlist[i].split(", ");
int k = 0;
for( ; k<15 && k<word.length; ++k ){
data[i][k] = word[k];
}
for( ; k<15; ++k ){
data[i][k] = "";
}
++i;
}
------解决思路----------------------
读文件内容,转成String[][]
public String[][] readFile(String strFile) {
ArrayList<String[]> tmp = new ArrayList<String[]>();
BufferedReader br = null;
try {
FileReader reader = new FileReader(strFile);
br = new BufferedReader(reader);
String strline = "";
while ((strline = br.readLine()) != null) {
tmp.add(strline.split(", "));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return tmp.toArray(new String[1][]);
}
输入String[][]
public void put(String[][] src){
for (int i = 0; i < src.length; i++) {
String[] strs = src[i];
for (int j = 0; j < strs.length; j++) {
System.out.print(strs[j]+"\t");
}
System.out.println();
}
}