Changing file path to a more common folder - java

I currently have a simple code in which i save a CSV file in a folder, according to my android studio monitor i am successfully saving that file in a folder i can't access which is "/storage/emulated/0/Download/myfolder/552.csv".
File path =new
File(Environment.getExternalStoragePublicDirectory(Environment. +
DIRECTORY_DOWNLOADS),"myfolder");
System.out.println(path);
if (!path.exists()){
path.mkdir();
}
File mypath=new File(path,(editSesion.getText().toString()+".csv"));
FileWriter mFile = new FileWriter(mypath,true);
CSVWriter writer = new CSVWriter(new FileWriter(mypath));
System.out.println(mypath);
Is there any way to obtain the path to a more commonly accesable folder?

/storage/emulated/0/Download/ is the Downloads folder of your phone storage.
How much common directory are you expecting than this?

Please add / (Forward slash) like this myfolder/
File(Environment.getExternalStoragePublicDirectory(Environment. +
DIRECTORY_DOWNLOADS),"myfolder");
change into
File(Environment.getExternalStoragePublicDirectory(Environment. +
DIRECTORY_DOWNLOADS),"myfolder/");

Related

Download file showing in tomcat bin folder

When I run my war file on Tomcat server then I run my project on chrome and download the xls file from my project and this file showing in tomcat bin folder as well as download folder in our computer.
Please suggest me how we can stop this download file in tomcat bin folder
thanks
String FILE_EXTENSION = ".xlsx";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
filename = "SearchPayment_Transactions_" + df.format(new Date()) + FILE_EXTENSION;
File file = new File(filename);
// this Writes the workbook
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.flush();
out.close();
wb.dispose();
fileInputStream = new FileInputStream(file);
addActionMessage(filename + " written successfully on disk.");
i think the this problem can be sovled, just by fixing the place you want to created the file
String FILE_EXTENSION = ".xlsx";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
filename = "SearchPayment_Transactions_" + df.format(new Date()) + FILE_EXTENSION;
File file = new File(path any fixed directory like temp\filename);
As long as you specify the path where you want to generate the file then it will generating only in tht directory. PLease make proper permission is given to path to generate file, and this will solve your issue.
The file appears twice on your computer, because your servlet code saves the *.xlsx file to disk before sending it to your browser. That's the behavior your chose in your code.
Remark however, that file in your code is a relative path, so the folder you write it is the working directory (according to the OS) of your server. The value of the working directory is not defined in the Servlet Specification and may vary from system to system.
A better solution would be:
either don't write any file at all and write your data directly to ServletResponse#getOutputStream(),
or write the file to the Servlet's temporary directory, which you can obtain through (File) servletContext.getAttribute(ServletContext.TEMPDIR). E.g. you can replace your file variable with:
final File file = new File((File) servletContext.getAttribute(ServletContext.TEMPDIR), filename);

Save a binary file in the same folder for every PC

I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");

Creating a series of Folders in sdcard android

My require file in sd card has path
Android/data/mypakagename/android/myfile/abc/myfile.txt
i have a url from where i will download this myFile.txt and place it in this location.
Right now I have directory Android/data/mypakagename/ created in sdCard.
Now i am using following code.
File file = new File("Android/data/mypakagename/android/myfile/abc/myfile.txt
");
file.mkdirs();
This creates all folders however it also create myfile.txt as a folder.I want to create all missing directories except last one. How can i do that?
File file = new File("Android/data/mypakagename/android/myfile/abc/myfile.txt
");
File parent = file.getParentFile();
parent.mkdirs();
String filename = "myfile.txt"
File dir = new File ("Android/data/mypakagename/android/myfile/abc");
dir.mkdirs();
File file = new File(dir, filename);

What is my directory when writing files in Android?

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes());
fos.close();
When trying to delete one of those files, this is what I use, but it's returning false.
String tag = v.getTag().toString();
File file = new File(System.getProperty("user.dir")+"/"+tag);
String s = new Boolean (file.exists()).toString();
Toast.makeText(getApplicationContext(), s, 1500).show();
file.delete();
How can I overcome this problem?
Use getFileStreamPath(FILENAME) to find your file. From the docs:
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
Your current working directory.
To help diagnose the problem, use file.getAbsolutePath() to see the full path.
It could also be a permissions problem, if you're trying to delete from another application. If so, you may need to change to MODE_WORLD_WRITEABLE (insecure), or restructure your code so the create and delete are called by the same app.
EDIT: That was mostly incorrect. I didn't realize that openFileOutput didn't use the current working directory.
Use same contents as 'FILENAME' variable in your first snippet in the second snippet while trying to delete.
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File RootFile = new File(RootDir);
RootFile.mkdir();
FileOutputStream f = new FileOutputStream(new File(RootFile, "Sample.mp4"));
i used this code to save the video files to non-default location. Hope this will be useful to you.By default it is storing in sd card
For each application the Android system creates a "data/data/package of the application" directory.
Files are saved in the "files" folder under this directory
to change the default directory the above code will be used
the default working directory can be displayed using fileobject.getAbsolutePath()

Java: How to create a new folder in Mac OS X

I want to create a folder in ex. my desktop in Mac OS X
I try to use this code, instead of Mymac is my name of course:)
String path="/Users/Mymac/Desktop";
String house = "My_home";
File file=new File(path);
if(!file.exists())
file.mkdirs(); // or file.mkdir()
file=new File(path + "/" + house);
try {
if(file.createNewFile())
{
}
} catch (IOException ex) {
ex.printStackTrace();
}
Do you know how I could create a new folder?
And another thing is when I want to create a folder in the directory where my code is, do you know how I could write that? I have tried
String path="./";
String path="::MyVolume";
String path=".";
A platform-independent way:
File rootDir = File.listRoots()[0];
File dir = new File(new File(new File(rootDir, "Users"), "Mymac"), "Desktop");
if (!dir.exists()){
dir.mkdirs();
}
Your code is ok and will work. Perhaps you have a typo in your username in your file-path ("Mymac"), so you don't see the changes, since they go to another folder.
Running this code on my machine works fine and gives the expected result.
To make your code platform-independant, you can build your file-path with the following trick:
File path = new File(File.listRoots()[0], "Users" + System.getProperty("file.separator") + "Mymac" + System.getProperty("file.separator") + "Desktop"));
If "My_home" should be a folder and not a file, you have to change the file.createNewFile() - command. More detailed information you'll find in the answer of Thomas.
To find the folder/directory where one of your classes is (assuming they are not in a Jar), and then to create a subfolder there:
String resource = MyClass.class.getName().replace(".", File.separator) + ".class";
URL fileURL = ClassLoader.getSystemClassLoader().getResource(resource);
String path = new File(fileURL.toURI()).getParent();
String mySubFolder = "subFolder";
File newDir = new File(path + File.separator + mySubFolder);
boolean success = newDir.mkdir();
(The code above could be made more compact, I listed it more verbosely to demonstrate all the steps.) Of course, you need to be concerned about permission issues. Make sure that the user which is running java has permission to create a new folder.
Use file.mkdir() or file.mkdirs() instead of file.createNewFile() and it should work, if you have permission to create new folders and files.
mkdirs() will create the subfolders if they don't exist, mkdir() won't.
To create a directory in your base directory (the one you start your application from), just provide a relative path name: new File("mydir").mkdir();
Edit: to make file handling easier, I'd suggest you also have a look at Apache Commons' FilenameUtils and FileUtils.

Categories