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.
Related
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");
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 try to write a text to a file and read this text later. When I use FileWriter I become a NullPointerException?
Is that a permission problem or ...? I also try the PrintWriter but I see the same Exception
.
This my code:
FileWriter fw = new FileWriter(new File("file.file"));
fw.write("XYZ");
best regards
londi
I guess your problem is that you use a relative file path, but that the origin of the relative path is not the one you think.
First of all, try to use an absolute path, that would be, on linux-like machines something like /home/me/myCode/myfile.txt or on windows something like c:/some/path/myfile.txt
Another thing you can do, in order to know what happens is print the origin.
File origin = new File(".");
System.out.println(origin.getAbsolutePath());
Once you know where the origin is, you can see what you need in order to get to your file.
Hope it will help.
Sounds like a permission issue. On iOS your application lives within a security sandbox, so you cannot just randomly read and write files anywhere you want. You could either use File.createTempFile to create a temp file somewhere hidden you your sandbox where nothing else can see it, or use the native api to determine where to dump your files. The following example will give you a file reference to the Documents Directory folder:
NSArray nsa = NSFileManager.defaultManager().URLsForDirectory$inDomains$(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask);
NSURL nsu = (NSURL)nsa.getFirst();
String snsu = nsu.getAbsoluteString() + "MyNewDocument.pdf";
File newFile = new File(new URI(snsu));
a simple question, I have the following java code:
File file = new File("myFile.xls");
file.renameTo("mySecondFile.xls");
System.out.println(file.length());
If I run it, I see that the file has changed of name correctly, but strangely file.length() returns 0 (And the file is not empty)
Any idea?
Thank you
File is immutable. It will always point to the filepath you created it with.
So when you rename your file, the file to which your File object points doesn't exist anymore (it was renamed) and you get the file length of 0.
See also the javadoc.
Try this:
File file = new File("myFile.xls");
file.renameTo("mySecondFile.xls");
File file2 = new File("mySecondFile.xls");
System.out.println(file2.length());
I think I am really close, but I am unable to open a file I have called LocalNews.txt. Error says can't find file specified.
String y = "LocalNews.txt";
FileInputStream fstream = new FileInputStream(y);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Name of file is LocalNews.txt in library called News....anyone know why the file will not open?
The file is in the same Java Project that I am working on.
Error: LocalNews.txt (The system cannot find the file specified)
Project is named Bst, package is src in subPackage newsFinder, and library that the text files are stored in is called News.
Found out it was looking in
C:\EclipseIndigoWorkspace1\Bst\bin\LocalNews.txt
But I want it to look in (I believe)
C:\EclipseIndigoWorkspace1\Bst\News\LocalNews.txt
But if I make the above url a string, I get an error.
String y = "LocalNews.txt";
instead use
String y = "path from root/LocalNews.txt"; //I mean the complete path of the file
Your program can probably not find the file because it is looking in another folder.
Try using a absolute path like
String y = "c:\\temp\\LocalNews.txt";
By 'library called News' I assume you mean a jar file like News.jar which is on the classpath and contains the LocalNews.txt file you need. If this is the case, then you can get an InputStream for it by calling:
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("LocalNews.txt");
Use
System.out.println(System.getProperty("user.dir") );
to find out what your current directory is. Then you'll know for sure whether your file is in the current directory or not. If it is not, then you have to specify the path so that it looks in the right directory.
Also, try this -
File file = new File (y);
System.out.println(file.getCanonicalPath());
This will tell you the exact path of your file on the system, provided your file is in the current directory. If it does not, then you know your file is not in the current directory.