关于java中文件输入输出流的问题
一个简单的复制文件的程序,把e:/test1/java.doc 中的内容复制到 e:/test2/java.doc ,直接读取字节内容时可以完美复制,字体的格式什么的都可以复制成功。但是当我定义一个字符串变量str,使得str等于按字节读取的e:/test1/java.doc 文件中的内容后,再把str中的内容 输出到文件2中去,这时候文件2中就成了乱码了。
求解,是不是str 不应该是String 格式的,那应该是什么格式的
import java.io.*;
public class FileDemo {
public static void main (String[]args){
File source = new File("e:/test1/java.doc");
File target = new File("e:/test2/java.doc");
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis =new FileInputStream(source);
fos =new FileOutputStream(target);
byte[] bytes =new byte[1024];
int length;
while((length=fis.read(bytes))!=-1){
String str = new String(bytes,0,length);
System.out.println(str);
byte[] by = str.getBytes();
fos.write(by);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(fis != null){
try{
fis.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (fos != null){
try{
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}