error in else block for directory copy - java

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
}

Related

Recursion method continues after returning value?

I'm writing a quick Java recursion method that, given a root folder and filename, searches your files for said file name.
import Java.io.File;
public static String searchForFile(File currentFolder, String filename)
{
try
{
File[] path = currentFolder.listFiles();
for (int i = 0; i < path.length; i++)
{
if (path[i].isDirectory())
{
System.out.println("Directory: " + path[i].toString());
searchForFile(path[i], filename);
}
else
{
System.out.println("File: " + path[i].toString());
if(path[i].getName().equals(filename))
{
System.out.println("Your file has been found!";
return path[i].toString();
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null; // Omitting this line yields compiling errors, not sure why?
}
public static void main(String[] args)
{
System.out.println("Hello, enter the root folder and file name.");
String rootFolder = "Desktop";
String fileName = "Hello.txt";
File f = new File("C:\\Users\\Me\\" + rootFolder);
searchForFile(f, fileName);
}
The program itself technically works, however searchForFile() keeps iterating even after the requested file is found. For example, I'd get an output such as:
File: C:\Users\Me\Desktop\My Stuff\NotHello.txt
**File: C:\Users\Me\Desktop\My Stuff\Hello.txt**
Your file has been found!
File: C:\Users\Me\Desktop\My Stuff\AlsoNotHello.txt
File: C:\Users\Me\Desktop\My Stuff\StillNotHello.txt
File: C:\Users\Me\Desktop\My Stuff\WhyIsThisMethodStillRunning.txt
I've been scratching my head at this for awhile now. I thought return always exits the method, so why does the recursion continue even after it returns a value? I haven't found any similar questions asked, so any help would be much appreciated!
(Also, how could I edit the method so that it returns a blank "" string if the requested file is not found?)
You are returning from the innermost call, when you've found the file. But when you are scanning a directory, you are not using the return value.
Change this:
searchForFile(path[i], filename);
to:
String result = searchForFile(path[i], filename);
if (result != null) {
return result;
}
The return null; in the bottom of your method is there because all methods needs to return a value. No matter if the file is found or not. If the file is not found within the current directory (or one of its subdirectories), you can return null; to indicate that it wasn't found.
Side suggestion: Use Optional in Java 8 instead of null.

How to access/get the value of a Variable inside a nested if statement to outside the main if statement

I have this code sample which I was developing. Here I have declared two variables (initialPath, lastPath) outside the main if-else statement. Inside the main If statement there is a nested if-else statement. I have initialized the variable (initialPath) inside the nested if statement. I need that value to be used outside the nested if-else statement. I have attached my code snippet. If anyone can help to solve my problem, I'd be glad :)
FileWriter writer;
File initialPath=null;
File lastPath=null;
if (clicked == 1) {
int sf = savefile.showSaveDialog(null);
if (sf == JFileChooser.APPROVE_OPTION) {
initialPath=savefile.getSelectedFile(); // in here the Variable values is initialized/assigned
try {
if (savefile.getFileFilter().equals(filter2)) {
String path = savefile.getSelectedFile() + ".java";
File file = new File(path);
writer = new FileWriter(file, false);
System.out.println(savefile.getFileFilter());
writer.write(jTextPane1.getText());
writer.close();
} else if (savefile.getFileFilter().equals(filter)) {
System.out.println("2");
String path = savefile.getSelectedFile() + ".txt";
File file = new File(path);
writer = new FileWriter(file, false);
writer.write(jTextPane1.getText());
writer.close();
} else {
System.out.println("No format");
}
} catch (IOException e) {
e.printStackTrace();
}
} else if (sf == JFileChooser.CANCEL_OPTION) {
clicked = 0;
}
} else {
try {
lastPath=initialPath.getParentFile(); //but in here lastPath become NULL because initialPath is NULL...
//I need to get the value of initialPath to this ELSE statement
if (savefile.getFileFilter().equals(filter2)) {
String path = savefile.getSelectedFile() + ".java";
File file = new File(path);
writer = new FileWriter(file, false);
System.out.println(savefile.getFileFilter());
writer.write(jTextPane1.getText());
writer.close();
} else if (savefile.getFileFilter().equals(filter)) {
String path = savefile.getSelectedFile() + ".txt";
File file = new File(path);
writer = new FileWriter(file, false);
writer.write(jTextPane1.getText());
writer.close();
} else {
System.out.println("No format");
}
} catch (Exception e) {
e.printStackTrace();
}
Is it possible for you to move initialPath=savefile.getSelectedFile(); outside of the if statement?
initialPath=savefile.getSelectedFile();
if (sf == JFileChooser.APPROVE_OPTION) {
...
}
else {
...
}
You can use initialPath outside as you declared it outside. " I need that value to be used outside the nested if-else statement."
In a short example what you are doing:
File file;
if(true){
file = /*you initialize here*/;
} else {
/*if false file is never initialized but you want to use it here,
its in scope but null of course.*/
}
Initialize file outside if you need it in both if and else blocks, if you can not initialize it outside you should not need that in the else block. A logical error is there.

Result of 'File.mkdirs()' is ignored

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.

Value inserted into a Map does not remain there in the second loop of a cycle

The funciton below copies all files with given extension from rootDirectory into given destination. It works well when names of the files differ, however when there are two files with the same name (see the recurvive call - it can be in the subdirectory), it does not do what it should. If there are more files with the same name, it should copy both and rename the second (adding _1, _2,... to its name).
I see there might be a problem with the Map I am using - every time a file is copied, I want to save it's name and add counter that counts how many times it has been copied (so the appropriate number can be added to its name). Could you please help me to fix the problem?
void copy(File rootDirectory, String destination, String fileExtension) {
File destFile = new File(destination);
HashMap<String, Integer> counter = new HashMap<>();
for (File file : rootDirectory.listFiles()) {
try {
if (file.isDirectory()) { copy(file, destination, fileExtension);
} else if (getExtension(file.getPath().toLowerCase()).equals(fileExtension.toLowerCase())) {
if (!destFile.exists()) { destFile.mkdirs();}
String fileName = file.getName();
if(counter.containsKey(fileName)){ // <<-- IS NEVER TRUE
int count = counter.get(fileName);
count++;
counter.put(fileName, count);
int i = fileName.contains(".") ? fileName.lastIndexOf('.') : fileName.length();
fileName = fileName.substring(0, i) + "_" + count + fileName.substring(i);
} else{ counter.put(fileName, 0);
}
Files.copy(file.toPath(), Paths.get(destination + "\\" + fileName), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
//...
}
}
}
You are using recursion. In other words you always start from a new empty Map. Put the map outside of your method and that will solve your problem.

java copy file functions only works in debug mode

I have a piece of code to copy a specific file, I've used this functions for ages and it works properly.
The problem is that right now I'm writing a program with java awt/swing and my copyFile functions only works in debug mode...I can't understand why..
This is the error it throws:
can't copy directory: QQQ.wav
source file is unreadable: QQQ.wav
Error occoured QQQ.wav (The system cannot find the file specified)
But when I run the program in debug mode it works..!!
could anyone help me please???
Function copyFile:
public static void copyFile(File varFromFile, File varToFile) throws IOException {
// First make sure the source file exists, is a file, and is readable.
if (!varFromFile.exists())
System.err.println("no such source file: " + varFromFile);
if (!varFromFile.isFile())
System.err.println("can't copy directory: " + varFromFile);
if (!varFromFile.canRead())
System.err.println("source file is unreadable: " + varFromFile);
// If the destination is a directory, use the source file name
// as the destination file name
if (varToFile.isDirectory())
varToFile = new File(varToFile, varFromFile.getName());
// If the destination exists, make sure it is a writable file
// and ask before overwriting it. If the destination doesn't
// exist, make sure the directory exists and is writable.
if (varToFile.exists()) {
if (!varToFile.canWrite())
System.out.println("destination file is unwriteable: "
+ varToFile);
} else {
// If file doesn't exist, check if directory exists and is
// writable. If getParent() returns null, then the directory is
// the current directory. so look up the user. Directory system
// property to
// find out what that is.
// The destination directory
String varParent = varToFile.getParent();
// If none, use the current directory
if (varParent == null)
varParent = System.getProperty("user.dir");
// Convert it to a file.
File vardir = new File(varParent);
if (!vardir.exists())
System.out.print("destination directory doesn't exist: "
+ varParent);
if (vardir.isFile())
System.out
.print("destination is not a directory: " + varParent);
if (!vardir.canWrite())
System.out.print("destination directory is unwriteable: "
+ varParent);
}
// If we've gotten this far, then everything is okay.
// So we copy the file, a buffer of bytes at a time.
// Stream to read from source
FileInputStream varFromSource = null;
// Stream to write to destination
FileOutputStream VarToDestination = null;
try {
// Create input stream
varFromSource = new FileInputStream(varFromFile);
// Create output stream
VarToDestination = new FileOutputStream(varToFile);
// To hold file contents
byte[] buffer = new byte[4096];
// How many bytes in buffer
int bytes_read;
// Read until EOF
while ((bytes_read = varFromSource.read(buffer)) != -1)
VarToDestination.write(buffer, 0, bytes_read);
//System.out.println("File copied !!!");
} catch (Exception e) {
System.err.println("Error occoured " + e.getMessage());
} finally {
if (varFromSource != null) {
try {
varFromSource.close();
} catch (IOException e) {
System.err.println("Error is " + e.getMessage());
}
}
if (VarToDestination != null) {
try {
VarToDestination.close();
} catch (IOException e) {
System.err.println("Error is " + e.getMessage());
}
}
}

Categories

Resources