我的程序是接收到数据之后写入文件,数据都接收到了,但是为什么没有写入到文件(图片)呢?这是我的代码
System.out.println("run"); String path2 = android.os.Environment.getExternalStorageDirectory()
.toString()
+ "/EasyCoder" + "/" + name + ".png";
        File file=new File(path2);
        try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}

int length2 = 0;
byte[] buf2 = new byte[1024];
try {
DataOutputStream fileOut = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(path2))); while (true) {
int read = 0;
if (in != null) {
read = in.read(buf2);
}
System.out.println(read);
if (read == -1) {
break;
}
fileOut.write(buf2, 0, read);

}
            
fileOut.flush();
fileOut.close();
in.close(); } catch (Exception e) {
e.printStackTrace();
}

解决方案 »

  1.   

    我不是太清楚为什么你要用DataOutputStream来做,而且in这个变量也不知道如何获取到的
    在我这里用这个DataOutputStream还是可以实现复制图片的,我想如果你那里有问题,可能在in这个变量上面
    我的代码如下import java.io.*;public class DataOutputStreamTest {
        public static void main(String[] args){
            System.out.println("run");        String path1 = "resources/images/thu3.jpg";
            String path2 = "resources/images/thu5.jpg";
            File file=new File(path2);
            try {
                file.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }        int length2 = 0;
            byte[] buf2 = new byte[1024];
            try {
                DataOutputStream fileOut = new DataOutputStream(
                        new BufferedOutputStream(new FileOutputStream(path2)));            DataInputStream in = new DataInputStream(
                        new BufferedInputStream(new FileInputStream(path1)));
                while (true) {
                    int read = 0;
                    if (in != null) {
                        read = in.read(buf2);
                    }
                    System.out.println(read);
                    if (read == -1) {
                        break;
                    }
                    fileOut.write(buf2, 0, read);            }            fileOut.flush();
                fileOut.close();
                in.close();        } catch (Exception e) {
                e.printStackTrace();
            }    }
    }
      

  2.   

    读取的是字节吗?
    DataOutputStream  用OutputStream 不就行了