Android creating a filename path from user input - java

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.

Related

Grails 3 Loading Static Files

I have a few PDF files in the assets folder of a Grails 3 application. I want to load them when the user clicks some button. i.e User clicks button "Get first book", and a grails controller looks for all files in the assets folder until it finds a match, and then returns the correct one.
Currently, I am loading the files by directly accessing the path. i.e. I am using an explicit aboslute path. According to this post, this is one of the advisable approaches. However, I want to load a file in grails by asking my application to get all assets in the asset folder, instead of using any paths.
My question then is, is it possible to get all files from the assets folder in a simple manner like we can get properties in the yml file (grailsApplication.config.someProperty)
Found the solution here: Grails : getting assets local storage path inside the controller
The following sample:
def assetResourceLocator
assetResourceLocator.findAssetForURI('file.jpg')?.getInputStream()?.bytes
worked fine for me.
this code makes something similar for me (however, my files are located outside of my project directory). Its a controller method, that receives the file name (id) and the filetype (filetype) and looks in a predefined directory. I think you just have to adapt your "serverLocation" and "contentLocation".
To get a list of the files, which you can pass to the view:
List listOfNewsletters = []
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File f = new File(serverLocation);
if (f.exists()) {
f.eachFile() { File file ->
listOfNewsletters.push([
path: file.path,
filename: file.name,
filetype: "pdf"
])
}
}
To deliver the file:
def openNewsletter() {
if (params.id != null && params.filetype != null) {
String pdf = (String) params.id + "." + (String) params.filetype;
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File pdfFile =new File(serverLocation + pdf);
response.contentType = 'application/pdf' // or whatever content type your resources are
response.outputStream << pdfFile.getBytes()
response.outputStream.flush()
}
}

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");

List files from inside a packaged war

I have an .ear, a .jar and a .war packages. I am reading my servlet classes dinamically by inspecting the file system and registering the mappings.
The thing is it works for development, I am able to read the directories and the proper file names do be able to create the mappings. The problem is that if I package my ear It does not work:
Using new File( ... ).isDirectory()
to check if I am in a directory, returns always false for a valid directory path.
Using new File( ... ).listFiles()
to be able to list the files from a directory, returns always null for a valid directory path.
I have solved the directory checking issue by detecting an end path that does not end with an extension (for my purpose such verification is enough), but I am still not able to list the files from a given path.
Given this situation I have the question:
How can I list the file names at runtime from a package .war?
The current code:
private void addAllFiles( File dir, ArrayList<ConventionPath> list ) {
for ( File file : dir.listFiles() ) { // dir.listFiles() comes null here =/
String absolutePath = file.getAbsolutePath();
boolean isActionDir = ConventionFiles.isActionDir( absolutePath, fileSeparator );
boolean isActionFile = ConventionFiles.isActionFile( absolutePath );
if ( isActionDir ) {
addAllFiles( file, list );
}
if ( isActionDir || isActionFile ) {
ConventionPath conventionPath =
new ConventionPath( absolutePath, fileSeparator );
list.add( conventionPath );
}
}
}
Now I made it work.
Instead of accessing the file via the file system I used the servlet context (I suppose this is the correct way to go):
URL root = context.getResource( "/WEB-INF/classes/com/package/" );
// /default-host/WEB-INF/classes/
String rootPath = root.getPath();
// /WEB-INF/classes/
rootPath = rootPath.substring( rootPath.indexOf( "/WEB-INF" ), rootPath.length() );
And then recursively I get the information I want from the resources:
Set<String> resourcesPath = context.getResourcePaths( rootPath );

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 ;

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