当前位置: 代码迷 >> J2SE >> 求解。IO系统不解之2解决办法
  详细解决方案

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

热度:255   发布时间:2016-04-24 02:26:17.0
求解。。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,没必要自己再去调。
------解决方案--------------------
  相关解决方案