How to create/write file in the root of the Android device? - android

I found out that you can use something like this to create a file:
FileOutputStream fs = openFileOutput("/test.in", MODE_WORLD_WRITEABLE);
String s = "[Head]\r\n";
s += "Type=2";
byte[] buffer = s.getBytes();
fs.write(buffer);
fs.close();
When running the above code I get an IllegalArgumentException stating:
java.lang.IllegalArgumentException:
File /test.in contains a path
separator
and I'm guessing the "/" is not appreciated. I wanted the "/" since I need to write the file to the root directory of the device, as stated in the API in trying to follow:
A request is a textfile (UNICODE) with
the file extension ".in". The
application reads and parses the .in
file when it's placed in root
directory on the mobile device.
Question is: how do I place a file in the root-directory? I have been looking around for an answer, but haven't found one yet.

Context.openFileOutput is meant to be used for creating files private to your application. they go in your app's private data directory. you supply a name, not a path: "name The name of the file to open; can not contain path separators".
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)
as for your question, you can't write to / unless you're root:
my-linux-box$ adb shell ls -l -d /
drwxr-xr-x root root 2010-01-16 07:42
$
i don't know what your API is that expects you to write to the root directory, but i'm guessing it's not an Android API and you're reading the wrong documentation ;-)

You can add files with path in private directory like that
String path = this.getApplicationContext().getFilesDir() + "/testDir/";
File file = new File(path);
file.mkdirs();
path += "testlab.txt";
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(path,true));
write(myOutput, new String("TEST").getBytes());
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

I faced the same problem today
java.lang.IllegalArgumentException: File /test.txt contains a path separator
and when i tried the following it worked.
File inputFile = new File("/storage/new/test.txt");
FileInputStream isr = new FileInputStream(inputFile);
DataInputStream in = new DataInputStream(isr);
if(!inputFile.exists()){
Log.v("FILE","InputFile not available");
}
else
{
while((line = in.readLine()) != null)
{
........ //parse
}
}
(Btw, I was getting this problem outside /root dir and while searching i saw this post)

Related

FileNotFoundException while reading an uploaded file

I'm trying to convert an IOS App to Android. I have no experience in Android so it may be a silly question. Sorry for that:)
I've uploaded some json files into the "files" folder of the emulator by device file explorer. (not into the external storage)
But when reading them, FileNotFoundException is thrown. (Permission denied) The code I used for reading is as below;
try {
File file = new File(getApplicationContext().getFilesDir() + "/Data/Users/profile.json");
FileReader fileReader = new FileReader(file);
String contents = "";
int i;
while((i = fileReader.read())!= -1) {
char ch = (char)i;
contents += ch;
}
return contents;
} catch (IOException e) {
e.printStackTrace();
}
I've tried to form those files programmatically in the same directory under "files" folder, as below.
String string = "{}";
File file = new File(getApplicationContext().getFilesDir() + "/Data/Users");
file.mkdirs();
File file2 = new File(getApplicationContext().getFilesDir() + "/Data/Users/profile.json");
file2.createNewFile();
FileOutputStream fos = new FileOutputStream(file2);
fos.write(string.getBytes());
fos.close();
This time, I managed to read them successfully by using the above code. It seems uploading files by device file explorer leads to some permission problems. I couldn't find how to modify them. How can I fix this?

Why does AssetManager list() not show my assets folder?

In my Android app I have packaged a file in the /assets folder that needs to be copied to the SDCARD. When I list the contents of the assets folder to a String[] I get "images", "sounds", "webkit" and "kioskmode" but not my file manually added to the assets folder.
My code is here:
private void copyAsset () {
AssetManager am = getApplicationContext().getAssets();
String[] files = null;
try {
files = am.list("");
} catch (IOException e) {
}
for (String filename : files) {
if (filename.equals("images") || filename.equals("kioskmode") ||
filename.equals("sounds") || filename.equals("webkit")) {
Log.i(TAG, "Skipping folder " + filename);
continue;
}
InputStream in = null;
OutputStream out = null;
try {
in = am.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory().getPath(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Error copying asset ", e);
}
}
}
Does it make a difference that this is a second class in my app and is called in my MainActivity using Intent showHelper = new Intent(this, HelperManager.class);
startActivity(showHelper); ?
I have tried the 2nd line (AssetManager am = ...) with and without the getApplicationContext() bit, tried moving the file into a subfolder of /assets and tried files = am.list("") with leading and trailing slashes. If I use a subfolder the files array is empty when the code runs (set a breakpoint on the files = am.list(""); line and inspected it at run time.
The strange thing is that it worked once - when I first wrote the code, but for further testing, I deleted the file from the /sdcard folder on the phone, and it never worked since even though the file is still in the assets folder.
I am using Android Studio if that matters.
Thanks
Managed to get a solution using Load a simple text file in Android Studio as a fix. It still puts the 4 folders in the files array but I Can skip them using code as given above, although I should rather check for the file I want rather than the 4 I don't!

I need to be able to store sound files for my application on sdcard

I've read a lot of topics but none seem to cover what I need.
I basically have a load of sound files and I want to be able to play them in the application from the sdcard.
I also want to be able to install them there in the first place when the application is installed.
I am using Eclipse with the android SDK and currently my Target project is v1.6
Can anyone help?
Thanks
OK so I found the answer!
First we need to get the external Storage Directory to a variable called baseDir.
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
Then Create the directory mysounds on the SDcard
File folder = new File(Environment.getExternalStorageDirectory() + "/mysounds");
boolean success = false;
if(!folder.exists())
{
success = folder.mkdir();
}
if (!success)
{
// Do something on success
}
else
{
// Do something else on failure
}
Then This following bit of code will copy all the files with sound at the beginning of the name from the assets directory to the mysounds directory you have already created.
try {
AssetManager am = getAssets();
String[] list = am.list("");
for (String s:list) {
if (s.startsWith("sound")) {
Log.d("Notice", "Copying asset file " + s);
InputStream inStream = am.open(s);
int size = inStream.available();
byte[] buffer = new byte[size];
inStream.read(buffer);
inStream.close();
FileOutputStream fos = new FileOutputStream(baseDir + "/mysounds/" + s);
fos.write(buffer);
fos.close();
}
}
}
Hope this helps someone!

Create a new file in Android emulator path /data/

I want to create a file in emulator android storage path /data/...
but it seems I can't create a new file by programs,
I should upload an empty file to /data/... and then write the file,
Can anyone help here?
openFileOutput("file.txt", MODE_PRIVATE) seems can create a new file in /data/data/Package/files/...
but it can't create in path /data/...
Thank you so much !
You cannot write directly to /data/ folder unless you have a rooted device. If you want to use /data/ directory then I would suggest using
/data/local/tmp/
This code can write a new file to the /data/data/Package/files/ folder. This may be the same with your code:
public void setparameter(int ilevel){
byte[] buffer = new byte[8];
buffer[0] = (byte)ilevel;
OutputStream output = null;
try{
output = openFileOutput("option.txt", MODE_WORLD_READABLE);
output.write(buffer);
output.flush();
output.close();
}catch (IOException e) { }
}

How to create files hierarchy in Androids '/data/data/pkg/files' directory?

I try to create 'foo/bar.txt' in Android's /data/data/pkg/files directory.
It seems to be a contradiction in docs:
To write to a file, call Context.openFileOutput() with the name and path.
http://developer.android.com/guide/topics/data/data-storage.html#files
The name of the file to open; can not contain path separators.
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String,%20int)
And when I call
this.openFileOutput("foo/bar.txt", Context.MODE_PRIVATE);
exception is thrown:
java.lang.IllegalArgumentException: File foo/bar.txt contains a path separator
So how do I create file in subfolder?
It does appear you've come across a documentation issue. Things don't look any better if you dig into the source code for ApplicationContext.java. Inside of openFileOutput():
File f = makeFilename(getFilesDir(), name);
getFilesDir() always returns the directory "files". And makeFilename()?
private File makeFilename(File base, String name) {
if (name.indexOf(File.separatorChar) < 0) {
return new File(base, name);
}
throw new IllegalArgumentException(
"File " + name + " contains a path separator");
}
So by using openFileOutput() you won't be able to control the containing directory; it'll always end up in the "files" directory.
There is, however, nothing stopping you from creating files on your own in your package directory, using File and FileUtils. It just means you'll miss out on the conveniences that using openFileOutput() gives you (such as automatically setting permissions).
You can add files with path in private directory like that
String path = this.getApplicationContext().getFilesDir() + "/testDir/";
File file = new File(path);
file.mkdirs();
path += "testlab.txt";
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(path,true));
write(myOutput, new String("TEST").getBytes());
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Use getFilesDir() to get a File at the root of your package's files/ directory.
To write to a file in a subfolder of internal storage you will need to create the file (and subfolder if not already there) first, then create the FileOutputStream object.
Here is the method I used
private void WriteToFileInSubfolder(Context context){
String data = "12345";
String subfolder = "sub";
String filename = "file.txt";
//Test if subfolder exists and if not create
File folder = new File(context.getFilesDir() + File.separator + subfolder);
if(!folder.exists()){
folder.mkdir();
}
File file = new File(context.getFilesDir() + File.separator
+ subfolder + File.separator + filename);
FileOutputStream outstream;
try{
if(!file.exists()){
file.createNewFile();
}
//commented line throws an exception if filename contains a path separator
//outstream = context.openFileOutput(filename, Context.MODE_PRIVATE);
outstream = new FileOutputStream(file);
outstream.write(data.getBytes());
outstream.close();
}catch(IOException e){
e.printStackTrace();
}
}
Assuming the original post sought how to both create a subdirectory in the files area and write a file in it, this might be new in the docs:
public abstract File getDir (String name, int mode)
Since: API Level 1
Retrieve, creating if needed, a new directory in which the application
can place its own custom data files. You can use the returned File
object to create and access files in this directory. Note that files
created through a File object will only be accessible by your own
application; you can only set the mode of the entire directory, not of
individual files.

Categories

Resources