Java使用FileInputStream和FileOutputStream编写复制粘贴程序,输出没有内容或者乱码,怎么回事?

/* 关于文件的复制和粘贴*/import java.io.*;public class Copy01{ public static void main(String[] args)throws Exception{//记得处理异常 //创建文件输入流 FileInputStream fls = new FileInputStream("temp01"); //创建文件输出流 FileOutputStream fos = new FileOutputStream("E:/temp01"); //边输入边输出(准备数组和temp) byte[] bytes = new byte[1024];//以1KB的速度 int temp = 0; while((temp=fls.read()) != -1){//循环输入 fos.write(bytes,0,temp);//写入输出 } //刷新输出流 fos.flush(); //关闭输入输出流 fls.close(); fos.close(); }}

第一点:你给的代码只是局部的并不完整,并不能整体分析问题。局部问题

1:获取输入流的文件名要是完整路径,否则出现异常

FileInputStream fls = new FileInputStream("temp01");

2:获取输出流的的路径同样也要精确到具体的文件也就是写的文件的完整地址,否则出现异常

FileInputStream fls = new FileInputStream("temp01");

3:循环将输入流的字节写入到输出流失要在函数fls.read中添加参数(与第三步骤正确代码比较一下)

while((temp=fls.read()) != -1){

第三步骤:完整的代码应该是这样的。

public static void main(String[] args) {

    //记得处理异常
    //创建文件输入流
    FileInputStream fls = null;
    // 创建文件输出流
    FileOutputStream fos = null;
    try {
        fls = new FileInputStream("E:/图片/1484293149528584.jpg");
        fos = new FileOutputStream("E:/file/1484293149528584.jpg");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // 边输入边输出(准备数组和temp)
    byte[] bytes = new byte[1024];
    //以1KB的速度
    int temp = 0;
    try {
        while((temp=fls.read(bytes)) != -1){
            //循环输入
            try {
                fos.write(bytes,0,temp);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //写入输出
            }

            //刷新输出流
            fos.flush();
            // 关闭输入输出流
            fls.close();
            fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

第三步骤:测试

1、控制台输出运行结果:

2、原始文件位置

3:拷贝文件位置:

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答