【Java中IO流】OutputStreamWriter的用法
最近复习了以下java的io流,发现有两个转换流, 分别为: InputStreamReader OutputStreamWriter , 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();
}
}
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();
}
}
}
}
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);
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(targetPath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] value = new byte[1024];
int len = -1;
while ((len = bis.read(value)) != -1) {
bos.write(value, 0, len);
}
bos.close();
bis.close();
}
}
package com.harderxin.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SwitchWriter
{
public static void main(String[] args) throws IOException
{
InputStream input = new FileInputStream(new File("C:\\local.png"));
OutputStream output =
new FileOutputStream("C:\\local_new.png");
byte[] img = new byte[1024];
while (input.read(img) != -1)
{
output.write(img, 0, img.length);
}
output.flush();
output.close();
input.close();
}
}
OutputStreamWriter output = new OutputStreamWriter(
new FileOutputStream("D:\\杂乱\\头像_new.jpg"));
String str = buff.toString();
output.write(str, 0, str.length());
写入的是字符,所以生成图片失败
这里不是应经 把字符流转换为字节流了吗, OutputStreamWriter output = new OutputStreamWriter(
new FileOutputStream("D:\\杂乱\\头像_new.jpg"));