读书人

求解。IO系统不解之2解决办法

发布时间: 2012-03-08 13:30:13 作者: rapoo

求解。。IO系统不解之2
上码。。。

Java code
import java.io.*;public class In {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        try{DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Test.txt")));out.writeBytes("somebody \n");     }catch(IOException e) {         System.out.println("No File!!!!!!!!");     }    }}

我用eclipse运行了下 确实生成了个Test.txt 但里边啥都没。。。 不死心 我又用javac编译了下 运行后还是只生成Test.txt文件 为什么呢 ??? 我明明输入了somebody \n 啊????
刚学IO 。。。。可能问题蠢了点 呵呵

[解决办法]
try
{
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Test.txt")));
out.writeBytes("somebody \n");
out.flush(); }
catch (IOException e)
{
System.out.println("No File!!!!!!!!");
}
[解决办法]
用到了BufferedOutputStream缓冲流,要么flush,要么close,才能写入到文件中
[解决办法]
IO里面绝大部分流是有缓冲机制,也就是先将数据写到缓冲区,缓冲区满了之后才真正写到文件
如果你数据量小,没有占满缓冲区,没有显示地执行flush()或者close()方法,那么数据不会写到文件

还有,IO部分操作的时候要有个好习惯,打开流之后一定记得关闭流,用try-catch-finally
Java code
/** * Created by IntelliJ IDEA. * User: admin * Date: 2011-10-10 * Time: 11:40:58 * To change this template use File | Settings | File Templates. */import java.io.*;public class In {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        DataOutputStream out=null;        try{            out= new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Test.txt")));            out.writeBytes("somebody \n");            out.flush();        }catch(IOException e) {            e.printStackTrace();//            System.out.println("No File!!!!!!!!");        }finally{            try{                out.close();            }catch(IOException e){                e.printStackTrace();            }        }    }}
[解决办法]
flush close() 加上应该可以
首先要清空缓冲区里的数据 再关闭流
[解决办法]
package com.qq.server.model;
import java.io.*;
public class MyQqServer
{
public static void main(String args[])
{
File f=new File("d:/t.txt");
FileOutputStream fos=null;
byte[] b=new byte[1024];
int n=0;
try {
fos=new FileOutputStream(f);
String s="aa ";
fos.write(s.getBytes());

} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
[解决办法]
上面是正解
[解决办法]
探讨

引用:

flush close() 加上应该可以
首先要清空缓冲区里的数据 再关闭流

为什么调用close和flush我查了下jdk api文档 我这里最外一层是DataOutputStream 他的方法没有close只有flush 那为什么大家说可以调用close呢。。。

[解决办法]
使用 close 就行,close 会调 flush,没必要自己再去调。
------解决方案--------------------


flush 是将缓冲区数据写入底层流再清空缓冲区。

读书人网 >J2SE开发

热点推荐