Result of 'File.mkdirs()' is ignored - java

This is my Code inside myDir.mkdirs(); this code show me that warning of Result of File.mkdirs() is ignored.
I try to fix this Warning but I failed.
private void saveGIF() {
Toast.makeText(getApplicationContext(), "Gif Save", Toast.LENGTH_LONG).show();
String filepath123 = BuildConfig.VERSION_NAME;
try {
File myDir = new File(String.valueOf(Environment.getExternalStorageDirectory().toString()) + "/" + "NewyearGIF");enter code here
//My Statement Code This Line Show Me that Warning
myDir.mkdirs();
File file = new File(myDir, "NewyearGif_" + System.currentTimeMillis() + ".gif");
filepath123 = file.getPath();
InputStream is = getResources().openRawResource(this.ivDrawable);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] img = new byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
while (true) {
int current = bis.read();
if (current == -1) {
break;
}
baos.write(current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
mediaScanIntent.setData(Uri.fromFile(new File(filepath123)));
sendBroadcast(mediaScanIntent);
}

The method mkdirs has a boolean return value, which you didn't use.
boolean wasSuccessful = myDir.mkdirs();
The create operation returns a value, which indicates if the creation of the directory was successful. For example, the result value wasSuccessful can be used to display an error when it is false.
if (!wasSuccessful) {
System.out.println("was not successful.");
}
From the Java docs about the boolean return value:
true if and only if the directory was created, along with all
necessary parent directories; false otherwise

File CDir = new File(Environment.getExternalStorageDirectory(), IMPORT_DIRECTORY);
if (!CDir.exists()) {
boolean mkdir = CDir.mkdir();
if (!mkdir) {
Log.e(TAG, "Directory creation failed.");
}
}
mkdir return a Boolean value. we need to catch the return value from mkdir .Replace your code with this and check (warning of Result of File.mkdirs() is ignored.) will be gone

The idea behind the return-value of mkdir is, that every IO-Operation could fail and your program should react to this situation.

You can do:
if(myDirectory.exists() || myDirectory.mkdirs()) {
// Directory was created, can do anything you want
}
or you can just remove the warning using:
#SuppressWarnings("ResultOfMethodCallIgnored")
The mkdirs method checks if file exists but returns false if the directory was already created so you should check one more time using first method.

File myDirectory = new File(Environment.getExternalStorageDirectory(),"NewyearGIF");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}else{
// Directory already exist
}

This is a old question but still, the simplest way I've found is:
File imageThumbsDirectory = getBaseContext.getExternalFilesDir("ThumbTemp");
if(imageThumbsDirectory != null) {
if (!imageThumbsDirectory.exists()) {
if (imageThumbsDirectory.mkdir()) ; //directory is created;
}
}

Just put this code:
File myDirectory = new File(Environment.getExternalStorageDirectory(),"NewyearGIF");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}else{
// Directory already exist
}
If application running in above Lollipop, then you need to add runtime permission for storage.

Related

Trouble copying file in Android

My problem is not How to make a copy of a File in Android, My problem is why it fails to make a copy.
After my app downloads a file am trying to copy it to another folder (The end user can save the file in several folder, that why i download once and copy to the rest). I do have the origin file path like:
/storage/emulated/0/MyAppFolder/FolderCreatedByUser1/theFile.pdf
And am trying to copy it to
/storage/emulated/0/MyAppFolder/FolderCreatedByUser2/
With this code (Code improved by Robert Nekic):
public static boolean copyFile(File src, File[] dst) {
boolean result = true;
if (src.exists()) {
String srcName = src.getName();
for (File file : dst) {
String to = file.getPath();
try {
File destination = new File(to, srcName);
if (destination.createNewFile()) {
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
dstChnl.transferFrom(srcChnl, 0, srcChnl.size());
srcChnl.close();
dstChnl.close();
} else {
result = false;
System.out.println("Unable to create destination " + destination.getPath());
}
} catch (Exception e) {
result = false;
System.out.println(e.getMessage());
break;
}
}
} else {
result = false;
System.out.println("File " + src.getPath() + " doesn't exist.");
}
return result;
}
The file exist, but am keep getting errors when copying it to the destiny file like:
/storage/emulated/0/MyAppFolder/FolderCreatedByUser2/theFile.pdf: open failed: ENOENT (No such file or directory)
It fails in both streams, when trying to open the src file and/or destination file:
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
Permission to write are granted. The destination folders are created previously to the download of the file, the user can't select a destination if the directory isn't created.
destination = new File(to, srcName); creates a new File instance but does not create the underlying file. You can verify by checking destination.exists(). I believe all you need is:
destination = new File(to, srcName);
destination.createNewFile();
Also, your src path string manipulation and stuff in the first half of your code seems unnecessary and might be introducing an error that could be resolved with something more concise:
public static boolean copyFile(File src, File[] dst) {
boolean result = true;
if (src.exists()) {
String srcName = src.getName();
for (File file : dst) {
String to = file.getPath();
try {
File destination = new File(to, srcName);
if (destination.createNewFile()) {
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
dstChnl.transferFrom(srcChnl, 0, srcChnl.size());
srcChnl.close();
dstChnl.close();
} else {
result = false;
System.out.println("Unable to create destination " + destination.getPath());
}
} catch (Exception e) {
result = false;
System.out.println(e.getMessage());
break;
}
}
} else {
result = false;
System.out.println("File " + src.getPath() + " doesn't exist.");
}
return result;
}

Javafx save textField to a text file

I have this code for saving to a text file however, I can't seem to find a way to make it save to not the user.home folder but to another folder on my hard drive. I searched in many places but couldn't really find anything that could help me.
It works with the user.home setting but if I try to change it, it doesn't. The program, when executed, comes up with Source not found.
saveBtn.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent event)
{
Object source = event.getSource();
String s = null;
//Variable to display text read from file
if (_clickMeMode) {
FileOutputStream out = null;
try {
//Code to write to file
String text = titleField.getText();
byte b[] = text.getBytes();
String outputFileName = System.getProperty("user.home"
+ File.separatorChar+"home")
+ File.separatorChar + "Movies2.txt";
out = new FileOutputStream(outputFileName);
out.write(b);
out.close();
//Clear text field
titleField.setText("");
}catch (java.io.IOException e) {
System.out.println("Cannotss text.txt");
} finally {
try {
out.close();
} catch (java.io.IOException e) {
System.out.println("Cannote");
}
}
}
else
{
//Save text to file
_clickMeMode = true;
}
window.setTitle("Main Screen");
window.setScene(mainScreen);
}
});
Your file name is incorrectly assigned:
String outputFileName = System.getProperty("user.home"
+ File.separatorChar+"home")
+ File.separatorChar + "Movies2.txt";
You are passing a string of the form "user.home/home" to System.getProperty().
Since there is no such property, this will return null.
Then you concatenate this with /Movies2.txt, so outputFileName will be something like null/Movies2.txt.
(A simple System.out.println(outputFileName) will confirm this.)
Instead of building the filename by hand like this, you should use a higher-level API to do it. E.g.:
Path outputFile = Paths.get(System.getProperty("user.home"), "home", "Movies2.txt");
OutputStream out = Files.newOutputStream(outputFile);
out.write(b);
If you also need (or might need) to create the directory, you can do
Path outputDir = Paths.get(System.getProperty("user.home"), "home");
Files.createDirectories(outputDir);
Path outputFile = outputDir.resolve("Movies2.txt");
OutputStream out = Files.newOutputStream(outputFile);
out.write(b);

File delete not working - it is only working one time that after restarting Jboss server and in debug mode

I am developing a System using Struts 1.x, Jsp Servlet and Pentaho(report generation).
Here when after generating report user can open and save that file as excel and that is working fine.
But problem occurs when a open a file, it creates file in our jboss temp folder that file is not deleted - that is the issue.
we are deleting file from code level and we figureout that after restating sever after first time it is deleting and other thing is when debugging it is deleting every time.
public Object process() throws RenderException, IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// properties for XSSF
File xmlFile = null;
File templateFile = null;
Writer xmlWriter = null;
boolean isXLSX = false;
timeStamp = Calendar.getInstance().getTimeInMillis();
try {
OutputType outputType = rendererAttrList.getOutputType();
Frame[] frameList = xmlDef.getShownFrames(renderDocs);
if (frameList != null) {
// ==============================================TPID#65448 code
// add========================================
boolean isPentahoExcel = false;
Frame t_CurrFrame = frameList[0];
if (t_CurrFrame != null) {
FrameType frameType = t_CurrFrame.getFrameType();
if (frameType == FrameType.FRAME_TYPE_EXTERNAL) {
isPentahoExcel = true;
}
}
// ==============================================TPID#65448 code end========================================
isXLSX = isXLSXOutput(frameList);
// native excel support and if the output is not supported by
// .xls, change the output to .xlsx
if (((outputType == OutputType.NATIVE_EXCEL2007) || ((outputType == OutputType.NATIVE_EXCEL97) && isXLSX))&&!isPentahoExcel)
{
workbook = new XSSFWorkbook();
rendererAttrList.setOutputType(OutputType.NATIVE_EXCEL2007);
xmlFile = File.createTempFile(getXmlDef().getName()
+ timeStamp, ".xml");
logger.info("XML File location :"
+ xmlFile.getAbsolutePath());
xmlWriter = new OutputStreamWriter(new FileOutputStream(
xmlFile), "UTF-8");
spreadSheetWriter = new SpreadsheetWriter(xmlWriter);
spreadSheetWriter.beginSheet();
} else {
workbook = new HSSFWorkbook();
}
dataFormat = workbook.createDataFormat();
sheet = workbook.createSheet("Report");
logger.debug("Start rendering the excel output in "
+ rendererAttrList.getOutputType() + " format ");
renderOutput();
logger.debug("Stop rendering the excel output ");
if (workbook instanceof HSSFWorkbook) {
// ==============================================TPID#65448 code add========================================
if (isPentahoExcel) {
renderExternalXLSX(t_CurrFrame,byteArrayOutputStream);
} else {
autoSizeColumn();
// write the excel to output
workbook.write(byteArrayOutputStream);
}
// ==============================================TPID#65448 code end========================================
} else {
// 1. generate data in XML format
spreadSheetWriter.endSheet();
// close the xml stream before we substitute in xlsx file
try {
if (xmlWriter != null)
xmlWriter.close();
xmlWriter = null;
} catch (Exception ex) {
logger.error("Error while closing xmlWriter for file "
+ xmlFile.getName());
}
// Step 2. create template from the excel workbook
String sheetRef = ((XSSFSheet) sheet).getPackagePart()
.getPartName().getName();
templateFile = createTemplate();
ByteArrayOutputStream xlsxOutput = new ByteArrayOutputStream();
// Step 3. Substitute the template entry with the generated
// data
substitute(templateFile, xmlFile, sheetRef.substring(1),
xlsxOutput);
// if the data is too large don't try to auto size the
// columns
// may result into out of memory exception
if (!isXLSX) {
// autosize the columns
InputStream inp = new ByteArrayInputStream(
xlsxOutput.toByteArray());
workbook = WorkbookFactory.create(inp);
sheet = workbook.getSheetAt(0);
autoSizeColumn();
if (xlsxOutput != null)
xlsxOutput.close();
byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
inp.close();
xlsxOutput.close();
} else {
byteArrayOutputStream = xlsxOutput;
}
}
}
} catch (Exception de) {
logger.error(de.getMessage(), de);
throw new RenderException(de.getMessage());
} finally {
try {
if (xmlWriter != null)
xmlWriter.close();
if (xmlFile != null)
xmlFile.delete();
if (templateFile != null){
templateFile.delete();
}
} catch (Exception ex) {
logger.error("Error while closing xmlWriter for file "
+ xmlFile.getName());
}
}
return byteArrayOutputStream;
}
Summary of my question - when Jboss restarting then first time and when debugging, temporary created file(temp directory) is deleting successfully .
but when it run normally it not deleting the file
but every time it is calling particular code level problem is why it doesn't perform.
templateFile.delete();
Thank you very much...
What happens when the delete method is called? You can log the output of the 'delete' method to see the result. It should be true or false.
Does it throw an exception? The delete method could throw a SecurityException indicating that you are denied access to delete the file.
In general, the first thing to do is try to understand why the file is not beeing deleted given the toolbox provided to you by this particular function.
Another approach could be to also call the deleteIfExists method instead. See here:
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#deleteIfExists-java.nio.file.Path-

error in else block for directory copy

I cannot for the life of me figure out what i am missing here. I am getting an error with the else block. I have tried all variation of brackets but cannot seem to get it to work. I need some fresh eyes to spot my mistake! Any ideas?
public static void makeCopies (File srcFolder, File destDirectory)throws Exception
{
if (srcFolder.isDirectory())
{
destDirectory.mkdir();
System.out.println("Directory copied from" +srcFolder + " to " +destDirectory);
}
String files[] = srcFolder.list();
for (String file : files)
{
File srcFile = new File(srcFolder, file);
File destFile = new File(destDirectory, file);
//recursive copy
makeCopies(srcFolder, destDirectory);
}
else {
FileInputStream sourceStream = new FileInputStream(srcFolder);
FileOutputStream destStream = new FileOutputStream(destDirectory);
// use an integer to transfer data between files
int transfer;
// tell the user what is happening
System.out.println("begining file copy:");
System.out.println("\tcopying " + srcFolder);
System.out.println("\tto " + destDirectory);
// read a byte, checking for end of file (-1 is returned by read at EOF)
while ((transfer = sourceStream.read()) != -1) {
// write a byte
destStream.write(transfer);
} // end while
// close file streams
sourceStream.close();
destStream.close();
System.out.println("File copy complete.");
}
you have all this chunk of code between the end of your if block and else block:
if
{
...
}
String files[] = srcFolder.list();
for (String file : files)
{
File srcFile = new File(srcFolder, file);
File destFile = new File(destDirectory, file);
//recursive copy
makeCopies(srcFolder, destDirectory);
}
else
{
...
}
this is not the right structure for if statement in java (or any C-like language for that matter).
it has to be this way:
if(condition) {
....
} else {
....
}
You're not closing your braces on the else block nor on the method block.
Your else isn't attached to any if. Assuming it's supposed to be the else for the if at the top of the method, just move the else { line up, immediately after you end your if block.
if (srcFolder.isDirectory())
{
destDirectory.mkdir();
System.out.println("Directory copied from" +srcFolder + " to " +destDirectory);
}
else { // Move it here
String files[] = srcFolder.list();
Or, if the code starting with String files[] = srcFolder.list(); (immediately after the current end if the if block) is meant to be part of the if, then move the closing if } down to the else.
Your for loop is outside of your if block, so the else you've written is seemingly part of the for loop instead. You're also missing a closing } for the else block.
What you have now:
if(){
}
for(){
}
else{
// this isn't attached to the if block...
}
what you should have:
if(){
// for loop can go here
}else{
// or here
}

Get files from Jar which is on the repository without downloading the whole Jar from Java

I would like to access the jar file on the repository, search inside it for the certain files, retrieve those files and store them on my hard disc. I don't want to download the whole jar and then to search for it.
So let's assume I have the address of the Jar. Can someone provide me with the code for the rest of the problem?
public void searchInsideJar(final String jarUrl, final String artifactId,
final String artifactVersion) {
InputStream is = null;
OutputStream outStream = null;
JarInputStream jis = null;
int i = 1;
try {
String strDirectory = "C:/Users/ilijab/" + artifactId +artifactVersion;
// Create one directory
boolean success = (new File(strDirectory)).mkdir();
if (success) {
System.out.println("Directory: " + strDirectory + " created");
}
is = new URL(jarUrl).openStream();
jis = new JarInputStream(is);
while (true) {
JarEntry ent = jis.getNextJarEntry();
if (ent == null) {
break;
}
if (ent.isDirectory()) {
continue;
}
if (ent.getName().contains("someFile")) {
outStream = new BufferedOutputStream(new FileOutputStream(
strDirectory + "\\" + "someFile" + i));
while(ent.)
System.out.println("**************************************************************");
System.out.println(i);
i++;
}
}
} catch (Exception ex) {
}
}
So, in upper code, how can I save the file I found(the last if) into directory.
Assuming that by "repository", you mean a Maven repository, then i'm afraid this can't be done. Maven repositories let you download artifacts, like jar files, but won't look inside them for you.

Categories

Resources