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");
Related
I've stumbled upon an issue that has been puzzling me. I'm writing an app that creates mp3 files on the external storage. The thing is, if I manually go to the created directory on the phone and delete the file, whenever I try to the create the same file it throws this error:
java.io.FileNotFoundException: /storage/emulated/0/Ringtones/sound1.mp3: open failed: EEXIST (File exists)
Selecting other sounds to be created works just fine, but after I manually delete them they can't be created again due to that issue.
I've already tried deleting the file right after indicating the path and before FileOutputStream but didn't work.
Any tips?
Cheers.
You need to acknowledge the media database before trying to create another copy of the same file. So you need to call this before copying:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(folder path in which your file was)));
Edit: The above answer is deprecated! Please use the following method:
File file = new File(outputPath + fileName);
String filePath = file.toString();
String mimeType = "video/mp4";
MediaScannerConnection.scanFile(this, new String[]{filePath}, new String[]{mimeType}, null);
Example of outputPath and fileName:
String outputPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "My App Name") + "/";
String fileName = "break dance" + ".mp4";
So the File file should be the path of the media you want to update either because it's just deleted or it's newly added, to be visible in Gallery.
Found the answer, following user blackapps' tip. I also changed the directory, as I was using a deprecated reference. Now it is working as intended for sdk 30.
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
I am programming a file transfer, and i am having troubles with it.
In my current location i have created a folder called "Server Folder", where i will have files that the Client can transfer (I will be transfered with the same name, to the workspace directory), But every time i try to access it, it fails.
FILE_SERVER_PATH = "./ServerFolder/";
File fileToRead = new File(FILE_SERVER_PATH + fileName);
fileToRead = fileToRead.getParentFile();
if(fileToRead.exists()){
FileInputStream readingBuffer = new FileInputStream(fileToRead);
fileName is received throw datagram, and the name is correct. It always fails in the condition --> fileToRead.exists()
Can anyone please give me a tip?
Thx! :-)
try to use the folder path as absolute.
will help and work...current directory works only if you know in which directory you are in at the time of execution.
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()
I'm trying to save a file in a subdirectory in Android 1.5.
I can successfully create a directory using
_context.GetFileStreamPath("foo").mkdir();
(_context is the Activity where I start the execution of saving the file) but then if I try to create a file in foo/ by
_context.GetFileStreamPath("foo/bar.txt");
I get a exception saying I can't have directory separator in a file name ("/").
I'm missing something of working with files in Android... I thought I could use the standard Java classes but they don't seem to work...
I searched the Android documentation but I couldn't fine example and google is not helping me too...
I'm asking the wrong question (to google)...
Can you help me out with this?
Thank you!
I understood what I was missing.
Java File classes works just fine, you just have to pass the absolute path where you can actually write files.
To get this "root" directory I used _context.getFilesDir(). This will give you the root of you application. With this I can create file with new File(root + "myFileName") or as Sean Owen said new File(rootDirectory, "myFileName").
You cannot use path directly, but you must make a file object about every directory.
I do not understand why, but this is the way it works.
NOTE: This code makes directories, yours may not need that...
File file = context.getFilesDir();
file.mkdir();
String[] array = filePath.split("/");
for (int t = 0; t < array.length - 1; t++) {
file = new File(file, array[t]);
file.mkdir();
}
File f = new File(file, array[array.length - 1]);
RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f, append);
Use getDir() to get a handle on the "foo" directory as a File object, and create something like new File(fooDir, "bar.txt") from it.