我有一个.txt文件,里面存有几百个1到100的数字(不知道具体多少个),中间都是用空格隔开的.我现在想把这些数字读出来存到一个数组或向量里,请问应该怎么做?我IO这部分学的不好,请多指教.谢谢.

解决方案 »

  1.   

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;public class FileToArray { public static void main(String[] args) {
    // TODO Auto-generated method stub
    int Temp;
    String str="";
    String mm[] = null;
    try{
    FileInputStream fis = new FileInputStream("G:\\workspace\\test\\filetoarray\\a.txt");
    while((Temp = fis.read())!=-1){
    str += (char)Temp;
    }
    mm = str.split(" ");
    }
    catch(FileNotFoundException e)
    {
    System.out.println(e);
    }
    catch(IOException e){
    System.out.println(e);
    }
    finally{
    for(int i = 0; i< mm.length; i++)
    {
    System.out.println(mm[i]);
    }
    }
    }}
      

  2.   

    中间只有空格么?不考虑有换行的话可以这么写:
    File f = new File("test.txt") ;
    BufferedReader in = new BufferedReader( new FileReader(f) ) ;
    String s = in.readLine() ;
    String[] ss = s.split(" ") ;
    int[] count = new int[ss.length] ;
    for (int i = 0; i<ss.length; i++)
    {
    count[i] = new Integer(ss[i]) ;
    }
    最后的count[]就是得到的数组
      

  3.   

    考虑分行情况,以下程序经测试是正确的
    /**文件路径
     * @param path
     * @return
     * @throws IOException
     */
    public int[] readnumber(String path) throws IOException{
    File file=new File(path);
    if(!file.exists()||file.isDirectory())
    throw new FileNotFoundException();
    BufferedReader br=new BufferedReader(new FileReader(file));
    String temp=null;
    StringBuffer sb=new StringBuffer();
    temp=br.readLine();
    while(temp!=null){
    sb.append(temp+" ");
    temp=br.readLine();
    }
    String[] array_str=sb.toString().split(" ");
    int[] array_int=new int[array_str.length];
    for(int i=0;i<array_str.length;i++)
    array_int[i]=Integer.parseInt(array_str[i]);
    return array_int;
    }