51,410
社区成员
发帖
与我相关
我的任务
分享package tv.lufei.copy;
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 Test {
public static void main(String[] args) throws IOException {
//读取要复制的文件内容
File file = new File("F:\\测试\\1.jpg");
InputStream reader = new FileInputStream(file);
byte [] b = new byte[2560];
int len = 0;
StringBuilder sb = new StringBuilder();
while ((len = reader.read(b)) != -1) {
String str = new String(b, 0, len);
sb.append(str);
}
// 4.释放资源
reader.close();
//创建并复制文件
File copyFile = new File("F:\\测试\\2.jpg");
File m = copyFile.getParentFile();
if(!m.exists()) {
m.mkdirs();
System.out.println("创建了"+m+"文件夹");
}
if(!copyFile.exists()) {
copyFile.createNewFile();
System.out.println("创建了"+copyFile+"文件");
}
OutputStream os = new FileOutputStream(copyFile);
// 2.1 准备要写入的数据
String str = sb.toString();
// 2.2 将要写入的字符串转换为byte数组
byte[] bytes = str.getBytes();
os.write(bytes);//将字节数组全部写入
// 4.释放资源
os.close();
System.out.println("复制成功");
}
}
File file = new File("F:\\测试\\1.jpg");
InputStream reader = new FileInputStream(file);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
byte [] b = new byte[2560];
int len = 0;
//StringBuilder sb = new StringBuilder();
while ((len = reader.read(b)) != -1) {
bos.write(b, 0, len);
}
//System.out.println(bos.toByteArray());
bos.close();
//System.out.println(sb.toString().getBytes().length);
// 4.释放资源
reader.close();
//创建并复制文件
File copyFile = new File("F:\\测试\\2.jpg");
File m = copyFile.getParentFile();
if(!m.exists()) {
m.mkdirs();
System.out.println("创建了"+m+"文件夹");
}
if(!copyFile.exists()) {
copyFile.createNewFile();
System.out.println("创建了"+copyFile+"文件");
}
OutputStream os = new FileOutputStream(copyFile);
// 2.1 准备要写入的数据
//String str = sb.toString();
// 2.2 将要写入的字符串转换为byte数组
byte[] bytes =bos.toByteArray();
//System.out.println(bytes.length);
os.write(bytes);//将字节数组全部写入
// 4.释放资源
os.close();
System.out.println("复制成功");