find file upload path in jsp - java

Can any body explain this code? i am confused please guide me and explain this code easy wording in JSP language .Thanks
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("<h3>Uploaded Filename:</h3> "+fileName);
}
}

In java file path can be described by \\.
For example: String path = "D:\\folder1\\folder2\\filename.type"
lastIndexOf("\\") will return the last position value of \\ from your file name.
The variable file will be assigned the path from which the file is going to be uploaded in the java program from your disk.
The if and else blocks check the file path is correct and it assigned the variable path.
Finally write method uploads the file from specified path.

First refer documentation of methods - lastIndexOfand substring lastIndexOf & substring to understand what these methods do.
Also note that we use double slashes in code due to \ being escape character so \\ means single slash \
If you apply, lastIndexOf("\\") , you might get either value -1 or >=0 . -1 value would mean that \ is not present in that String and value >=0 means that it is present.
In this below if part, you simply determine if \ is there in fileName , if it is there - take only last portion and append with filePath so for a fileName with value like abc\test.txt you are extracting only \test.txt and appending to filePath.
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}
Then , in else part, we already know that \ is not present in so code is unnecessarily doing - fileName.lastIndexOf("\\")+1) - this will always be zero.
else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
So code can simply be written as ,
else{
file = new File( filePath +fileName)}
line - new File(....) creates a File object that is where stream contents get written to.
On SO, these kind of questions don't get answered but I answered since your profile says that you are a student.
Secondly, I can't comment if that code is correct or incorrect, I simply explained what that code is doing.

Related

Getting the right slash for each platform

I have a JFilechooser to select a filename and path to store some data. But I also want to store an additional file in the same path, same name but different extension. So:
File file = filechooser.getSelectedFile();
String path = file.getParent();
String filename1 = file.getName();
// Check the extension .ext1 has been added, else add it
if(!filename1.endswith(".ext1")){
filename2 = filename1 + ".ext2";
filename1 += ".ext1";
}
else{
filename2 = filename1;
filename2 = filename2.substring(0, filename2.length-4) + "ext2";
}
// And now, if I want the full path for these files:
System.out.println(path); // E.g. prints "/home/test" withtout the ending slash
System.out.println(path + filename1); // E.g. prints "/home/testfilename1.ext1"
Of course I could add the "/" in the middle of the two strings, but I want it to be platform independent, and in Windows it should be "\" (even if a Windows path file C:\users\test/filename1.ext1 would probably work).
I can think of many dirty ways of doing this which would make the python developer I'm carrying inside cry, but which one would be the most clean and fancy one?
You can use the constants in the File class:
File.separator // e.g. / or \
File.pathSeparator // e.g. : or ;
or for your path + filename1 you can do
File file = new File(path, filename1);
System.out.println(file);
Just use the File class:
System.out.println(new File(file.getParent(), "filename1"));
You can use:
System.getProperty("file.separator");

Two similar copy codes with Java, two behaviors

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 ;

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: Get URI from FilePath

I've little knowledge of Java. I need to construct a string representation of an URI from FilePath(String) on windows. Sometimes the inputFilePath I get is: file:/C:/a.txt and sometimes it is: C:/a.txt. Right now, what I'm doing is:
new File(inputFilePath).toURI().toURL().toExternalForm()
The above works fine for paths, which are not prefixed with file:/, but for paths prefixed with file:/, the .toURI method is converting it to a invalid URI, by appending value of current dir, and hence the path becomes invalid.
Please help me out by suggesting a correct way to get the proper URI for both kind of paths.
These are the valid file uri:
file:/C:/a.txt <- On Windows
file:///C:/a.txt <- On Windows
file:///home/user/a.txt <- On Linux
So you will need to remove file:/ or file:/// for Windows and file:// for Linux.
Just use Normalize();
Example:
path = Paths.get("/", input).normalize();
this one line will normalize all your paths.
From SAXLocalNameCount.java from https://jaxp.java.net:
/**
* Convert from a filename to a file URL.
*/
private static String convertToFileURL ( String filename )
{
// On JDK 1.2 and later, simplify this to:
// "path = file.toURL().toString()".
String path = new File ( filename ).getAbsolutePath ();
if ( File.separatorChar != '/' )
{
path = path.replace ( File.separatorChar, '/' );
}
if ( !path.startsWith ( "/" ) )
{
path = "/" + path;
}
String retVal = "file:" + path;
return retVal;
}
The argument to new File(String) is a path, not a URI. The part of your post after 'but' is therefore an invalid use of the API.
class TestPath {
public static void main(String[] args) {
String brokenPath = "file:/C:/a.txt";
System.out.println(brokenPath);
if (brokenPath.startsWith("file:/")) {
brokenPath = brokenPath.substring(6,brokenPath.length());
}
System.out.println(brokenPath);
}
}
Gives output:
file:/C:/a.txt
C:/a.txt
Press any key to continue . . .

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
}

Categories

Resources