import java.io.*;
public class TestOutStream
{
public static void main(String [] args)
{
int b;
FileOutputStream out = null;
FileInputStream in =null;
try 
{
in = new FileInputStream("F:/123/11111.txt");
out = new FileOutputStream("F:/123/22222.txt");
}catch(FileNotFoundException e)
{
System.out.println("没有文件");
System.exit(-1);
}
try
{
while((b=in.read())!=-1)
{

out.write(b);//如果这里不强制转换成(char)b他给我输出一群数字,求解(char)b即把int型转换成char原因及原理
}
out.close();
in.close();//求解,如果我这里不写想和两个close(),可以编译,也可以运行,而且不会抛异常,请问那我写他们有什么用么,不写会有什么后果
}catch(IOException eee)//求解,这里的IOException什么情况下能补到错误,IOException具体有什么错误呢
{
System.out.println("出错了");
System.exit(-1);
}

}
}

解决方案 »

  1.   

    首先,正常的输入输出不是你这么写的。
    while((b=in.read())!=-1)
    {
     out.write(b);
    }
    1. 你往输出文件中写的内容时 b(int 类型,该类型是存储数字的),而char类型数存储单个字符。 
       正常写的内容应该是byte类型的,只有这样才能中输出文件中原来输入文件的内容
    2. 输入、输出流是需要关闭的,它是占系统资源的
    3. IOException 该异常的产生环境很多,比如文件突然不存在了,又或者没有权限等
      

  2.   

    请教个正版写输入,输出流while((b=in.read())!=-1)
    {
     out.write(b);
    }
    的写法
      

  3.   

    这样写问题也不大的。char字符其实就是ascii码转义的。例如 字符'a'好像是ascii码97吧。你可以试下
    int i = (int)'a'  i就是97  就是这样转义的。关闭连接是为了防止占用连接资源以及连接冲突 有些连接你不关闭的话 其他地方就不能使用了。
    如果出现I/O错误或数据流不支持读取操作,就产生IOException异常
      

  4.   

    关键你从输入流中读取的长度是int类型(32位),但输出时转换成了char(16位),会有内容丢失的
      

  5.   


    InputStream fins = new FileInputStream(fromPath);
    OutputStream fouts = new FileOutputStream(toPath);
    byte[] buf = new byte[1024];
    int i = 0;
    while ((i = fins.read(buf)) != -1) {
    fouts.write(buf, 0, i);
    }
    fins.close();
    fouts.close();
      

  6.   


    //供参考
    import java.io.*;class Test
    {
    public static void main(String [] args)
    {

    FileOutputStream out = null;
    FileInputStream in =null;
    try  
    {
    in = new FileInputStream("d:\\1.txt"); //抛出FileNotFoundException
    out = new FileOutputStream("d:\\2.txt"); //抛出FileNotFoundException
    byte [] buf = new byte[1024];
    int len = 0;

    while((len=in.read(buf))!=-1) //抛出IOException
    {
    out.write(buf,0,len); //抛出IOException
    }
    }
    catch(IOException e) //FileNotFoundException是IOException的子类
    {
    e.printStackTrace();
    }
    finally
    {
    try
    {
    if(in!=null)
    in.close();
    }
    catch(IOException e)
    {
    throw new RuntimeException("文件读取失败!");
    }

    try
    {
    if(out!=null)
    out.close();
    }
    catch(IOException e)
    {
    throw new RuntimeException("文件存储失败!");
    }
    }

    }
    }