java 中有一个名为 .createTempFile
的方法,我将其用于生成图片并返回文件的方法。这是代码的一部分:
File jpgFile = File.createTempFile("tmp, ".jpg");
//fill the file with information ...
return jpgFile;
当我在主方法中访问该方法时,我得到一个文件。现在我的问题是:如何保存此文件?我尝试这样做:
File f = generateJPG(); // (the method that is explained above)
File out = new File("C:/fileJPG.jpg");
FileInputStream fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileWriter fstream = new FileWriter(out, true);
BufferedWriter outw = new BufferedWriter(fstream);
String aLine = null;
while ((aLine = in.readLine()) != null) {
outw.write(aLine);
outw.newLine();
}
in.close();
outw.close();
但这行不通,只会给我一张非常混乱的图片,里面充满了随机像素。那么如何将此临时文件保存到我的计算机呢?
我刚刚找到了解决方案。我用了ImageIO
和BufferedImage
,就像@JordiCastilla说的那样,它工作得很好。这是代码:
File f = generateJPG();
BufferedImage image = ImageIO.read(f);
File out = new File("C:/fileJPG.jpg");
ImageIO.write(image, "jpg", out);