编写和重命名已读取和修改的文件

时间:2014-04-13 09:49:48

标签: java bufferedimage naming

我的作业要求我编写一个程序来读取命令行中给出的图像(图像在运行程序之前保存在项目文件夹中),然后平铺并更改图像上的颜色和使用-tiled后缀保存此新文件。

我唯一能在Stack Overflow上找到的是使用renameTo方法,但是对于变量'inputfile'所属的类型BufferedImage未定义,因此当前代码将无法编译。

File outputfile = inputfile.renameTo(inputfile + "-tiled");
try {
    ImageIO.write(inputfile1, "png", outputfile);
} catch (IOException e) {
    e.printStackTrace();
}

有什么更好的方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

不要重命名该文件;您需要创建一个新文件,就像使用File构造函数一样,文件名为String

// --- READ ---
File inputFile = new File(args[0]);
BufferedImage image = ImageIO.read(inputFile);

// --- PERFORM IMAGE MANUPULATION --- 
...

// --- DERIVE NAME --- 
String inputPath = inputFile.getPath();
// do string manipulation to turn into outputPath (using "-tiled")
File outputFile = new File(outputPath);

// --- WRITE ---
ImageIO.write(image, "png", outputFile);

来自write方法的JavaDocs:

  

使用支持给定格式的任意ImageWriter将图像写入File。如果已存在文件,则其内容将被丢弃。

因此它会自动创建一个新文件。请注意,File实例不直接表示文件句柄。它们只是文件的虚拟表示;真实文件仅在写入时创建。