Trying to create a file to save an image Java
I get the following exception when trying to create a file on windows 7 using Java. An example of a path is "C:/g-ecx/images-amazon/com/images/G/01/gno/images/orangeBlue/navPackedSprites-US-22.V183711641.png". If I hard code in a path it does work however. I've been banging my head for two hours, can anyone help.
mkdir fails but doesn't through an exception, create file throws the exception.
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);
开发者_如何学JAVA } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try using
boolean mkdir = file.mkdirs();
instead of
boolean mkdir = file.mkdir();
mkdirs() creates the whole parent path/directories if needed:
精彩评论