这是我的测试计划。我需要它适用于某处。这可能很小,对不起。但我仍然是首发。所以请帮助我。
try{
File file1 = new File("c:\\Users\\prasad\\Desktop\\bugatti.jpg");
File file2 = new File("c:\\Users\\prasad\\Desktop\\hello.jpg");
file2.createNewFile();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String data = null;
StringBuilder imageBuild = new StringBuilder();
while((data = reader.readLine())!=null){
imageBuild.append(data);
}
reader.close();
BufferedWriter writer = new BufferedWriter(new PrintWriter(new FileOutputStream(file2)));
writer.write(imageBuild.toString());
writer.close();
}catch(IOException e){
e.printStackTrace();
}
答案 0 :(得分:1)
您可以执行以下任一操作:
private static void copyFile(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
或者如果您想使用流,可能是这样:
private static void copyFile(File source, File dest)
throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} finally {
input.close();
output.close();
}
}
答案 1 :(得分:1)
图片不包含行甚至字符。因此,您不应该使用readLine()
甚至Readers
或Writers.
您应该直接使用输入和输出流重写复制循环。