java - How to automatically create missing folders for ImageOutputStream? -


i'm trying save jpg images custom compression. therefore using imagewriter follows:

imageoutputstream os = new fileimageoutputstream(new file(filenamepath));  imagewriter jpgwriter = imageio.getimagewritersbyformatname("jpg").next(); imagewriteparam jpgwriteparam = jpgwriter.getdefaultwriteparam(); jpgwriteparam.setcompressionmode(imagewriteparam.mode_explicit); jpgwriteparam.setcompressionquality(1f); jpgwriter.setoutput(os); 

problem: code works if folder given in filenamepath exists, , throws filenotfoundexception if folder missing.

question: how implicit let writer create target folder?

you need create first. fileimageoutputstream won't create file if doesn't exist.

this can done using java nio.2 api files.createdirectory(dir). method checks if directory exists and, if not, creates it.

creates new directory. check existence of file , creation of directory if not exist single operation atomic respect other filesystem activities might affect directory.

if need create parent directories well, can use files.createdirectories(dir):

creates directory creating nonexistent parent directories first.

sample code:

file.createdirectories(paths.get(filenamepath)); 

note better idea use java nio.2 api instead of old createnewfile(): can handle rights give created directories. also, forces developer handle case directories couldn't created (and gives more information why, instead of having true or false in createnewfile() case).


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -