根据你的代码改了下,输出没问题。
public class ReadTxt {
public static void main(String[] args) {
String filePath = "C:/1.xls";
InputStream fs = null;
Workbook workBook = null;
String[][] array = null;
try {
fs = new FileInputStream(filePath);
workBook = Workbook.getWorkbook(fs);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int col = 0;
int row = 0;
Sheet[] sheets = workBook.getSheets();//获取sheet总数
for (int n = 0; n < sheets.length; n++) {
Sheet sheet = sheets[n];
if (sheet.getRows() == 0) {//如果没数据则跳过
continue;
}
array = new String[sheet.getRows() - 3][2];
Cell cell = null;
for (int j = 3; j < sheet.getRows(); j++) {
row = 0;
for (int i = 3; i < 6; i++) {
cell = sheet.getCell(i, j);
if (i != 4) {
array[col][row] = cell.getContents();
row++;
}
}
col++;
}
}
workBook.close();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("array[" + i + "," + j + "]" + array[i][j]);
}
}
}
}
java读取txt文件然后赋值二维数组实现方法如下:
package shi;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test13 {
/**
* 读取文件
* @param filePath
* @return
*/
public static List readTxtFile(String filePath) {
List
try {
String encoding = "UTF-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
if (!lineTxt.startsWith("#"))
list.add(lineTxt);
}
read.close();
} else {
System.out.println("找不到文件");
}
} catch (Exception e) {
System.out.println("出错了");
e.printStackTrace();
}
return list;
}
/**
* 创建二维数组
* @param list
* @return
*/
public static String[][] createArray(String filePath){
List
String array[][] = new String[list.size()][];
for(int i=0;i
String linetxt=list.get(i);
String[] myArray = linetxt.replaceAll("\\s+", "@").split("@");
for(int j=0;j
array[i][j]=myArray[j];
}
}
}
return array;
}
/**
* 打印数组
* @param array
*/
public static void printArray(String array[][]){
for(int i=0;i
System.out.print("array["+i+"]["+j+"]="+array[i][j]+",");
}
else{
System.out.print("array["+i+"]["+j+"]="+array[i][j]);
}
}
System.out.println();
}
}
public static void main(String args[]) {
String array[][] = createArray("F:\\test1.txt");
printArray(array);
}
}