试图创建一个文件来保存图像Java

时间:2011-07-03 18:40:03

标签: java file-io io javax.imageio

尝试使用Java在Windows 7上创建文件时出现以下异常。路径的示例是“C:/ g-ecx / images-amazon / com / images / G / 01 / gno / images / orangeBlue / navPackedSprites-US-22。 V183711641 .png”。如果我在路径中硬编码,它确实有效。我一直在敲我的头两个小时,任何人都可以帮忙。

mkdir失败但没有通过异常,create file抛出异常。

java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processImage(ImageProcessingBehavior.java:125)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.loadImages(ImageProcessingBehavior.java:99)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processNodes(ImageProcessingBehavior.java:66)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processRootNode(ImageProcessingBehavior.java:34)
at org.willmanning.mtt.html.ParsingFacade.processURL(ParsingFacade.java:38)
at org.willmanning.mtt.App.main(App.java:45)



 /**
 * 
 * @param image
 * @param url
 */
public void processImage(BufferedImage image, URL url) {

    StringBuilder path = new StringBuilder();
    path.append("C:/Users/will/Documents/");
    path.append(url.getHost().replace('.', '/'));
    path.append(url.getFile());
    path.replace(path.lastIndexOf("."), path.length(), ".txt");

    File file = new File(path.toString());

    boolean mkdir = file.mkdir();

    boolean isNew = false;
    try {
        isNew = file.createNewFile();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    /*
     * only create the file if it doesn't exist
     */
    if (isNew) {
        try {
            ImageIO.write(image, "jpg", file);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

尝试使用

boolean mkdir = file.mkdirs();

而不是

boolean mkdir = file.mkdir();
如果需要,

mkdirs()创建整个父路径/目录: