在练习JAVA IO读取和写入文件流的时候发现了一个问题,小弟像大家请教,写入的时候完全正常,在读取String类型的文件的时候也正常,但是在读取int型文件的时候发现,读取出来的数据,不是写入的数据,请问各位大侠是哪里出错了?
代码如下:
写入的代码:PrintWriter outputStream=null;
try {
outputStream=new PrintWriter(new FileOutputStream("f:\\number.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("OutPutStream is begining");
outputStream.println(1);
outputStream.println(2);
outputStream.println(3);
outputStream.close();
System.out.println("OutPutStream is closed");
读取的代码:BufferedReader inputStreams=null;
try {
inputStreams=new BufferedReader(new FileReader("f:\\sally.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// String line="";
int number=0;
int count=0;
System.out.println("BufferedReader is begining");
try {
while(inputStreams.ready())
{
number=inputStreams.read();
System.out.println(number);
count++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
inputStreams.close();
System.out.println("inputStreams is closed");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(line);
System.out.println("Has "+count+" lines");
控制台输出的时候:
OutPutStream is begining
OutPutStream is closed
BufferedReader is begining
39532
19996
38451
65292
22823
31528
34507
13
10
39532
19996
38451
65292
22823
31528
34507
13
10
97
100
109
105
110
13
10
97
112
116
101
99
104
13
10
39532
19996
38451
65292
22823
31528
34507
13
10
97
100
109
105
110
13
10
97
112
116
101
99
104
13
10
39532
19996
38451
65292
22823
31528
34507
13
10
97
100
109
105
110
13
10
97
112
116
101
99
104
13
10
39532
19996
38451
65292
22823
31528
34507
13
10
97
100
109
105
110
13
10
97
112
116
101
99
104
13
10
39532
19996
38451
65292
22823
31528
34507
13
10
97
100
109
105
110
13
10
97
112
116
101
99
104
13
10
39532
19996
38451
65292
22823
31528
34507
13
10
97
100
109
105
110
13
10
97
112
116
101
99
104
13
10
39532
19996
38451
65292
22823
31528
34507
13
10
97
100
109
105
110
13
10
97
112
116
101
99
104
13
10
inputStreams is closed
Has 177 lines
谢谢各位大侠了~~

解决方案 »

  1.   

    你写入的是f:\number.txt
    你读出的是f:\sally.txt
      

  2.   

                while(inputStreams.ready())
                {
                    number=inputStreams.read();
                    System.out.println(number);
                    count++;
                }估计上面这一段有问题,不知道你count++是用来做什莫的建议这样来读
    BufferedReader br = new BufferedReader(new FileReader("f:\\sally.txt"));
    String temp = "";
    while((temp = br.readLine())!=null){
    System.out.println(temp);
    }