怎样从文本文件中读数据?
txt文本中存有数据如下:
950 582 439 360 285 27 156 836 76 48 978 367
代码段:
  public void start() {
    File filePath = new File ("DataIn.txt");
    FileInputStream fileIS ;
    DataInputStream dataIS ;
    //FileReader fr ;
    int j = 0;    try {
      fileIS = new FileInputStream(filePath);
      //fr = new FileReader (filePath);
      dataIS = new DataInputStream (fileIS);
      //dataIS = new DataInputStream (filePath);
      for (int i = 0 ; i<4 ;i++) {
        j = dataIS.readInt();
        //j = fr.read();
        System.out.println(j);
      }
      dataIS.close();
      fileIS.close();
    } catch(FileNotFoundException e) {
      System.out.println("File Not Found!");
    } catch(IOException eIO) {
      System.out.println("Can not read any Int!");
    }
  };
将以上数据存入DataIn.txt文件,执行程序,想定的输出是:
950
582
439
360
实际输出为:
959787017
892875273
875772169
859189257
我也看过DataInputStream.readInt()方法,对方法中有移位的操作不太理解!
我也用过FileReader.read(),输出是:
9
5
05
8
2
……
在C++中有函数fscanf()可以完成以上操作,输出结果也正确。Java中有没有功能类似于C++中fscanf()的函数,可以直接读入一个int型数据?
请高手指教一二!感谢!

解决方案 »

  1.   

    用这个,我的是把aa.txt文件中的数据存入abc.txt中,运行是正确的
    import java.io.*;
    public class wj
    {
    public static void main(String args[])
    {
    try
    {

    String str;
    FileReader io=new FileReader("aa.txt");
           BufferedReader out=new BufferedReader(io);
    FileWriter fr=new FileWriter("abc.txt",true);
    PrintWriter pw=new PrintWriter(fr);

    str=out.readLine(); while(!str.equals(""))
    {
    str=out.readLine();
            pw.println(str);
            pw.flush();
    }
    out.close();
    pw.close();
        }catch(Exception e){
    }
    }}
      

  2.   

    DataInputStream不是这样用的,看它的readInt()函数:
        public final int readInt() throws IOException {
            int ch1 = in.read();
            int ch2 = in.read();
            int ch3 = in.read();
            int ch4 = in.read();
            if ((ch1 | ch2 | ch3 | ch4) < 0)
                throw new EOFException();
            return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
        }
    这个DataInputStream根本就不是用来从文本流中分析出数字的,它读取的对象是二进制流。
    看它首先读出四个字节(整型是四个字节嘛),再将第一个读出的值左移24位,成了int的最高8位,第二个读出的值左移16位,成了int的第9到第16位(从高位开始算)……如此把读出四个字节(虽说是int型,只有低8位有效,如果不是EOF,则这些int的高8位都是8)拼成最终的int值。Java好像没有哪个对象有楼主要的方法,自己写一个吧,也很简单啊!
      

  3.   

    感谢两位的回复!
    不过"deweyroy(马涛)"给的代码好象用不起来,运行后没有任何输出.
    看来只有听"BabyWhite(BabyWhite)"的自己写了,不过我想请问一下,我现在想到的方法
    是:将读到的非空格数据先存起来,当读到一个空格时,在将前面读到的数据串拼凑成需
    要的整数.不过,我觉得这种方法比较麻烦,请问有没有更简单有效的方法???