小弟刚学java,遇到该问题,
在txt文件中有一个矩阵如下:
1 2 3 4
5 6 9 8
1 5 6 6
7 8 9 6我想读出来,,存到一个二维数组中。可读出来都不是该数据,
我用到FileInputStream,建立文件连接,用一个DataInputStream,来读出,,怎么才能正确呢?谢谢

解决方案 »

  1.   

    FileInputStream tfile=new FileInputStream(Pathstr+"\\conndb.txt");
        int c;
        while ((c=tfile.read())!=-1)
        {
      str=str+(char)c;
        }
      

  2.   

    package funny.test ;import java.io.* ;
    import java.util.*;public class TestIO {

    public static void main(String[] args) {
    System.out.println("testing started") ;
    try {
    FileToArray fta = new FileToArray("D:\\test.txt") ;
    int[][] ra = fta.toInt2DArray() ;
    for( int i=0;i<ra.length;i++){
    for(int j=0;j<ra[i].length;j++){
    System.out.print(ra[i][j] + "\t") ;
    }
    System.out.println() ;
    }
    } catch (IOException e) {
    e.printStackTrace();
    }

    }

    }class FileToArray {

    private File file ;

    public FileToArray(String path) throws IOException {
    file = new File(path) ;
    if( ! file.exists()) {
    throw new IOException("file does not exist") ; 
    }
    }

    public int [][] toInt2DArray() {
    int max_x = 0 ;
    ArrayList<String[]> lines = new ArrayList<String[]>() ;

    try {
    BufferedReader br = new BufferedReader(new FileReader(file)) ;
    String line = null ;
    while( (line=br.readLine()) != null ) {
    String[] splitted = line.split(" ") ;
    if( splitted.length > max_x ) 
    max_x = splitted.length ;
    lines.add(splitted) ;
    }
    } catch (IOException e) {
    e.printStackTrace();
    }

    int [][] int2DArray = new int[lines.size()][max_x] ;

    for(int i=0;i<lines.size();i++) {
    String[] line = lines.get(i) ;
    for(int j=0;j<line.length;j++) {
    int2DArray[i][j] = Integer.parseInt(line[j]) ;
    }
    }

    return int2DArray ;
    }

    }
    将就用用吧.PS: 如果文件内容为 
    1 2 3 4 0 0 0
    5 6 9 8 0 0 0
    1 5 6 6 1 2 4
    7 8 9 6 0 0 0 则得到的数组为 1 2 3 4 0 0 0
    5 6 9 8 0 0 0
    1 5 6 6 1 2 4
    7 8 9 6 0 0 0
      

  3.   

    请教:
    ArrayList<String[]> lines = new ArrayList<String[]>() ;
    我的Eclipse 会报错,为什么?Multiple ers at this line
    - The type ArrayList is not generic; it cannot be parameterized with arguments <String[]>
    - Syntax error, parameterized types are only available if source level is 5.0
    - The type ArrayList is not generic; it cannot be parameterized with arguments <String[]>
    - Syntax error, parameterized types are only available if source level is 5.0
      

  4.   

    用JDK5.0编译即可,泛式用1.4的话下面的
    ArrayList<String[]> lines = new ArrayList<String[]>() ;
    改成
    ArrayList lines = new ArrayList() ;即可
    还有后面的程序可做个类型转换
    String[] line = lines.get(i) ;
    要改为
    String[] line = (String[])lines.get(i) ;