日期:2014-05-20  浏览次数:20760 次

【Java中IO流】OutputStreamWriter的用法
最近复习了以下java的io流,发现有两个转换流, 分别为: InputStreamReader OutputStreamWriter , OutputStreamWriter是将输入的字符流变为字节流, 我写了一个例子,但怎么行不通? 麻烦大家看一下:

public class SwitchWriter
{
    public static void main(String[] args) throws IOException
    {

        InputStream input = new FileInputStream(new File("D:\\杂乱\\头像.jpg"));

        StringBuffer buff = new StringBuffer();
        byte[] img = new byte[1024];
        while (input.read(img) != -1)
        {
            buff.append(new String(img));
        }
        
        //生成图片失败,这时怎么回事啊?
        OutputStreamWriter output = new OutputStreamWriter(
                new FileOutputStream("D:\\杂乱\\头像_new.jpg"));

        String str = buff.toString();
        output.write(str, 0, str.length());

        output.flush();
        output.close();
        input.close();
    }
}
OutputStreamWriter

------解决方案--------------------
楼主虽然不不知道你代码错在哪,但是我帮你写了一个

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SwitchWriter {
    public static void main(String[] args) {
 
        FileInputStream input = null;
        FileOutputStream output = null;
try {
input = new FileInputStream(new File("D:\\杂乱\\头像.jpg"));
output = new FileOutputStream("D:\\杂乱\\头像_new.jpg");
    int a;
    while ((a = input.read()) != -1) {
          output.write(a);
    }
    output.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
        try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}

    }
}

------解决方案--------------------
OutputStreamWriter output = new OutputStreamWriter(
                new FileOutputStream("D:\\杂乱\\头像_new.jpg"));
 
        String str = buff.toString();
        output.write(str, 0, str.length());
写入的是字符,所以生成图片失败
------解决方案--------------------
看到楼主的分享了,我之前在学习流的时候也遇到过很多困惑,现在有些经验了跟楼主分享一下。
通常操作多媒体文件,流中是以二进制的格式进行的,所以建议使用字节流来操作,楼主的方式忽略了一下节点:
1.读的时候使用字节流,写的时候用的是字节转换流,这样的转换过程会发生问题的。
2.读的时候每一次往img数组中读入,然后添加的StringBuffered中的时候,最后一次有可能没有读满数组,所以会导致多余的字节,同时你是否也发现复制后的文件变大了。

我给楼主分享一版代码,希望对你有帮助:
public class SwitchWriter {
public static void main(String[] args) {
try {
copy("E:\\login_icon.png", "E:\\test.png");
} catch (IOException e) {
e.printStackTrace();
}
}

/**
 * 复制文件,使用字节流
 * 
 * @param sourcePath
 * @param targetPath
 * @throws IOException
 */
public static void copy(String sourcePath, String targetPath)
throws IOException {
FileInputStream fis = new FileInputStream(sourcePath);