Two similar copy codes with Java, two behaviors - java

So I wanted to implement a function that copies a file into a new file of which I'll specify the directory (I'll create it) and then, as I found on stackoverflow, use the Files.copy function of apache.commons to do the trick.
My problem is the following : I write two codes, one that works and the other don't, except they are so similar I seem not to capture the difference...
Here's the code for the first method :
public static void copyToFile2 (String firmFolderName, String allFirmsFolderName, String copy_file_name, String copied_file_name) throws IOException {
File from = new File(copied_file_name) ;
String pathOfDirectoryOfToFile= "Folder/" + allFirmsFolderName +"/" + firmFolderName ;
//String pathOfDirectoryOfToFile = "Folder/fomrs/firm/" ;
String pathOfToFile = pathOfDirectoryOfToFile + "/" + copy_file_name ;
(new File(pathOfDirectoryOfToFile)).mkdir();
File to = new File(pathOfToFile) ;
Files.copy( from.toPath(), to.toPath() );
}
In this one, I have to specify few parameters that will forge a path to a directory, create that directory and finally create the copy file in there. It throws a NoSuchFileException, and while I know the file doesn't not exist, I thought it might be nice and create it itself, but since it didn't : I went ahead and added to.createNewFile(); right after the to file instanciation to make sure, thus I'll have the following code :
(new File(pathOfDirectoryOfToFile)).mkdir();
File to = new File(pathOfToFile) ;
to.createNewFile();
Files.copy( from.toPath(), to.toPath() );
With this one, I get an IOException stating that the specified access path is not found !
Second method :
public static void copyToFile1 (String firmFolderName, String allFirmsFolderName, String copy_file_name, String copied_file_name) throws IOException {
File from = new File(copied_file_name) ;
String pathOfDirectoryOfToFile= "Folder/" + allFirmsFolderName +"/" + firmFolderName +"/" ;
String pathOfToFile = pathOfDirectoryOfToFile + "/" + copy_file_name ;
(new File("Folder/mdjs55/")).mkdir();
File to = new File("Folder/mdjs55/tm.jsp" ) ;
Files.copy( from.toPath(), to.toPath() );
}
In this one works fine.
So what is it ? The only difference I can not is that the path in the copyToFile2 is dynamic and in the second static, but how is that supposed to be a problem ? For what I know it's merely a string that's being build...
P.S : I used System.out.println(to.toPath()) to check out the path for that, it's well constructed.
Thanks in advance for your help.

The path in the second example is shorter. mkdir() will only create one sub-directory so if you go two sub-directories it will fail and when you try to use a file in that directory it will also fail.
I suspect what you want is mkdirs() which creates multiple-levels of directories as required.

This
String pathOfDirectoryOfToFile= "Folder/" + allFirmsFolderName +"/" + firmFolderName +"/" ;
String pathOfToFile = pathOfDirectoryOfToFile + "/" + copy_file_name ;
looks suspicious. It produces
"Folder/" + allFirmsFolderName +"/" + firmFolderName +"//" + copy_file_name ;

Related

java.io.File constructor behaviour or perhaps multithreading issue?

I have the following code:
class Abcd{
//wired by spring to give the directory filePath ="/var/tmp/"
private String filePath;
public void myMethod(String id, String date){
filePath= filePath+ id+ "_" + date;
File f = new File(filePath);
if(f.exists){//Do something}
else{
System.out.println("File not found at file path:"+filePath);
}
}
}
The above code is behaving weird , intermittently the filePath contains all the files of directory /var/tmp/ . So , if /var/tmp directory contains two files called "id1_01012017" and "id2_10102017".
This is the intermittent output
File not found at file path:/var/tmp/id1_01012017id2_10102017
Am unable to figure out whats happening
The best way to do this is to maintain that filePath remains immutable. You will find that if you change this line:
filePath = filePath + id + "_" + date;
to the following:
String tempFilePath = filePath + id + "_" + date;
and operate on tempFilePath instead of filePath, your code will become thread-safe and work as expected.

Generate filename for a copied file

I am looking to get similar behaviour to what you get in Windows when you copy and paste a file in the same directory.
For e.g, if you've copy/paste a file called foo.txt, it will create foo Copy.txt and if you paste it once more, it creates foo Copy(2).txt and if you copy/paste foo Copy.txt, foo Copy Copy.txt is created.
Is there a Java utility function that does this? I've looked at File.createTempFile but the filename it generates is too long and contains a UID-like substring.
By using the FileChooser in combination with the "showSaveDialog"-method you will get the result you want, because java is then using the OS behaviour for existing files.
Sometimes, you just have to do the work first, it will give you an appreciation for the API. Then you can write your own utility methods
File original = new File("build.xml");
String path = original.getAbsoluteFile().getParent();
String name = original.getName();
String ext = name.substring(name.indexOf("."));
name = name.substring(0, name.indexOf("."));
name = path + File.separator + name;
int index = 1;
File copy = new File(name + " (" + index + ")" + ext);
while (copy.exists()) {
index++;
copy = new File(name + " (" + index + ")" + ext);
}
System.out.println(copy);

Android creating a filename path from user input

I'm sure there is a simple answer to this but I'm new and can't seem to figure this out.
I need to save data to a text file. I have all the code to do that but the path and filename is hard-coded for now. I have an EditText field where the user enters the filename and then hits a button. I want it to create a path and filename based on what the user enters.
Basically a pre determined path of "/sdcard/"+Whateveruserentered.txt
Ok , here is a simple answer,
suppose you have entered "myPath/myfile.txt" in EditText,
First you need to create "myPath" folder ( I am assuming you are giving foldername too in path ).
String fullPath = myEditText.getText().toString().trim();
String folderPath = fullPath.substring ( 0, fullPath.indexOf ( "/" ) );
String fileName = fullPath.substring ( fullPath.indexOf ( "/" ) + 1 );
// First Create folder by coding,
File folder = new File(Environment.getExternalStorageDirectory().toString() + folderPath );
if (!folder.exists())
{
folder.mkdirs();
}
// Note: your path must not have recursive folders like myPath1/myPath2/myFile.txt, otherwise you need to create folder in 2 steps.
// Now creating file
File file = new File(Environment.getExternalStorageDirectory().toString() + folderPath + fileName );
if ( !file.exists() )
{
success = file.createFile();
}
// Now your file is created, you can do writing code now onwards.

Java. Files and folders. Can't define the type

Good Day!
I wrote the method in Java which must search files in folders and do some operations with them.
So the problem is that when I try to check what I have (file or dir) I receive nothing in both cases! But as i can see paths look correct.
How can I fix this problem?
Here is the code:
public void searchInDir(){
File inputFile = new File( this.fileName );
String[] namesOfFilesDir = inputFile.list();
for ( int i = 0; i < namesOfFilesDir.length; i++ )
{
String normalPath = this.getNormalPath(inputFile.getCanonicalPath()); //C:\User -> C:\\User
// Two separators for correcting path to file
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
System.out.printf("FileName=%s, Path=[%s]\n", namesOfFilesDir[i], pathToCurrentFile);
System.out.println(f.isDirectory());//False
System.out.println(f.isFile());//False too
//Some other code
}
}
For example this.fileName consists path to folder ( and this folder consists one folder and 2 files).
I got next:
FileName=Readme.txt, Path=[C:\\workspace\\Grep\\t\\Readme.txt]
false
false
FileName=t2, Path=[C:\\workspace\\Grep\\t\\t2]
false
false
FileName=test.txt, Path=[C:\\workspace\\Grep\\t\\test.txt]
false
false
Ok. Program says that.
Lets print next code as an example.
File f = new File("C:\\workspace\\Grep\\t\\Readme.txt");
System.out.println(f.isFile());
Program will print ”True”.
This part makes no sense:
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
Even if we forget about the double separator for the time being, it makes no sense to first construct the file name by adding namesOfFilesDir[i], then construct a File() object using the two-argument constructor which basically adds namesOfFilesDir[i] once more. Try printing f.getAbsolutePath() and you'll see what I mean. It should have probably been something like:
File f = new File( normalPath, namesOfFilesDir[i] );
Probably the file doesn't exist, so it is neither a file nor a directory. Try printing the output of f.exists() as well.
Did you notice the duplicate file separator in your path?
I think that perhaps your paths are not correct. Both isFile() and isDirectory() only return true if the file/directory actually exists. Have you tried calling exists() on the file? Also, I'm suspicious of what your getNormalPath() method is doing - I think it might be mangling the filenames.
The 1st System.out.println is missleading!
It would have been better to output the path of f.
Anyway, according the output:
FileName=Readme.txt, Path=[C:\workspace\Grep\t\Readme.txt]
f will be C:\workspace\Grep\t\Readme.txt\Readme.txt
that is, namesOfFilesDir[i] is being appended twice!
It would be easier/better to work just with instances of File directly:
File inputFile = new File(this.fileName);
File[] files = inputFile.listFiles();
for (File f : files) {
System.out.printf("FileName=%s, Parent=[%s]\n", f.getName(), f.getParent());
System.out.println(f.isDirectory());
System.out.println(f.isFile());
//Some other code
}

How do I refer to a directory in Java?

I'm running Windows and I'm trying to refer to a directory. My function starts off like this:
File file = new File("C:\\somedir\\report");
if (!file.exists()) {
file.mkdirs();
}
doStuffWith(file);
I got a NullPointerException within the doStuffWith function, when I tried to call listFiles. Well I looked in C:\somedir and what did I find - there is a file called "report" with no extension, and also a directory called "report"! What seemed to happen was that the file object was referring to the report file rather than the directory. How do I make sure that I am referring to the directory and not the file?
one way to go about is to pass the file object corresponding to "C:\somedir" to the method and inside the method, do a listFiles() and walk through the contents, each time checking for file name and if it is "report", do a isDirectory(). proceed with actual processing when this returns true.
i think there is a isDirectory() method that will tell you if it is a directory
--EDIt
that's what I get for being up so early. I ran your code locally and it works fine for me. Was able to create new files, read directory contents, etc. What else are you trying to do?
I don't understand the problem this works fine for me:
public class MkDir {
static void doStuff(File dir) {
if ( dir.isDirectory() ) {
File[] listFiles = dir.listFiles();
for ( File f : listFiles ) {
System.out.println( f.getName() );
}
}
}
public static void main(String[] args) {
File file = new File( "C:\\dev\\rep2\\rep" );
if ( !file.exists() ) {
file.mkdirs();
}
doStuff( file );
}
}
Check if your file system has had case sensitivity enabled (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\kernel\ dword:ObCaseInsensitive in the registry.)
If so, you may be getting bitten by a case-related issue. One way to check:
String someName = "./nameNotUsedYet";
boolean first = new File(someName).mkdirs();
boolean second = new File(someName.toUpperCase()).mkdirs();
System.out.println("first = " + first + ", second = " + second);
If both mkdirs() calls succeeded, you know you have a case related complication. If so, ensure that you get the case for "C:\somedir\report" exactly right.

Categories

Resources