How can I write a file with an android app? - android

I writing a cryptographic app that will generate a public private key pair for RSA. The private key needs to be saved on the device. In testing with a normal java application, the keys were generated and then saved to file with the following:
public static void saveToFile(String fileName,BigInteger mod, BigInteger exp) throws IOException
{
ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
try
{
oout.writeObject(mod);
oout.writeObject(exp);
}
catch (Exception e)
{
throw new IOException("Unexpected error", e);
}
finally
{
oout.close();
}
}
The key file would appear in the project directory. However, with the android app, this does not happen. How can I write a file with an android app?
Thanks!

The key file would appear in the project directory. However, with the android app, this does not happen. How can I write a file with an android app?
In Android, there are only two major places where your application can write files: it's private internal storage directory, and the external storage volume. You have to do more than just provide a file name, you must provide the full path that includes on of these locations.
//Internal storage location using your filename parameter
File file = new File(context.getFilesDir(), filename);
//External storage location using your filename parameter
File file = new File(Environment.getExternalStorage(), filename);
The difference being internal storage is only accessible by your app; external storage can be read/written from anywhere, including your PC if you connect and mount the storage over USB.
You can then wrap the appropriate file in the FileOutputStream of your existing code.

First pass main class from you call as method:
Boolean writfile;
writfile =savTextFileInternal(this.getApplicationContext(),"Maa","Ambika");
Toast.makeText(this, "File write:"+writfile, Toast.LENGTH_LONG).show();
Create a method like this:
public boolean savTextFileInternal(Context context,String sFileName, String sBody)
{
try
{
File root = new File(context.getFilesDir(),"myfolder");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
return true;
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
}

Related

Android App: Save a txt file that can be accessed through Explorer

I'm trying to create a txt file during the operation of my App which I then want to download onto my computer and assess the contents.
I've try both on the internal and external storage but I am still unable to find the text file after (when my tablet is plugged into my computer).
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("orp.txt",Context.MODE_WORLD_WRITEABLE));
outputStreamWriter.write(data);
outputStreamWriter.close();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"orp2.txt");
String tempS = file.getAbsolutePath();
file.setReadable( true, false );
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have found been able to find either ("orp.txt" or "orp2.txt"), but also I do not receive any error during the running of the app, and the app is able to open "orp.txt" at a later time, so I know is has been created.
I cant find files created unless using Eclipse file explorer, or maybe its the media scan that has to be triggered, can be done by restarting the device. Scans the files available on the device.
It may be the directory, this is what I do in my code.
File f = new File(cxt.getExternalFilesDir(filepath), fileName);
f.createNewFile();
FileWriter writer = new FileWriter(f);
writer.append(manNo+System.getProperty("line.separator"));
writer.append(dateTime);
writer.flush();
writer.close();
Thanks for the input but I found the answer was to do with the media scanner, "orp2.txt" appeared in my download folder after I restarted the device.
This answer and blog post helped
Android: save file to downloads that can be viewed later

What path does "getApplicationContext().getFilesDir()" return?

I'm doing a simple app in Android and in a certain part of the app I would like to create an Excel file and write in it. I've already prepared everything to use jexcel library to edit an excel using Java, but the thing is I can't find the Excel file I created. I've tried to find it in my own device executing the app, but I couldn't.
String fileName = "hours.xls";
File file = new File(getApplicationContext().getFilesDir() + fileName);
Can anybody help me please?
Thanks in advance :)
On Android KitKat, it returns /data/data/{your package name}/files, however I imagine this could change depending on your platform version. Thus if you're just trying to dig through your filesystem and see a file, it's safe to use this path, but if you're using this path for some functionality across multiple platform versions, you should only reference it using getFilesDir().
What are you planning on using this file for? Do you want it usable by other apps too? Using getApplicationContext().getFilesDir() will give you /data/data/com.package/files but if you want a file that's easily accessible by yourself and other apps, you're better off using something like getExternalFilesDir()
If you want to access your file via your PC (with an usb cable) or via a file manager on your device, prefer:
new File(getExternalFilesDir(null), fileName);
This folder is created in .../Android/data/ ... com.yoursociety.yourapp/files ...
null means that you do not want to store files in predefined folders like Movies, Pictures and so on.
(See documentation for more info)
This worked:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
b = (Brain)load("brain.txt");
if (b == null) {
b = new Brain();
}
vocabulary = (ArrayList <String>) load("vocabulary.txt");
if (vocabulary == null) {
vocabulary = new ArrayList <String> ();
vocabulary.add("I love you.");
vocabulary.add("Hi!");
}
b.setRunning(true);
}
public Object load(String fileName) {
File file = new File("/storage/emulated/0/Android/data/com.cobalttechnology.myfirstapplication/files/" + fileName);
if (!file.exists()) {
return null;
}
try {
Object o;
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
o = ois.readObject();
if (o == null) {
System.out.println(fileName + " = null");
}
ois.close();
fis.close();
System.out.println("Loaded: " + fileName);
return o;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return null;
}
public void save(Object o, String fileName) {
File file = new File("/storage/emulated/0/Android/data/com.cobalttechnology.myfirstapplication/files/" + fileName);
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(o);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Read the documentation, this method reads the files stored in the internal storage that were created with
with openFileOutput():
getFilesDir()
Returns the absolute path to the directory on the filesystem where
files created with openFileOutput(String, int) are stored.

Issue on appending a file in android

I am creating an android application which reads and writes data to a file in the location /sdcard/ReadandWrite/.when i writing to that file it does not write in append mode.it will removes the old data and writes the new one.please help me to solve this.Here is my code.
private File openfile() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/ReadandWrite");
dir.mkdirs();
File file = new File(dir, "myfile.txt");
file.setWritable(true);
if(file.exists())
{
file.canRead();
file.setWritable(true);
}
else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
private void writetofile() {
try {
File file=openfile();
OutputStreamWriter myOutWriter =
new OutputStreamWriter(new FileOutputStream(file));
myOutWriter.append(text.getText());
myOutWriter.close();
myOutWriter.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
You need to configure the FileOutputStream to use append mode. From JDK documentation:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Creates a file output stream to write to the file with the specified
name. If the second argument is true, then bytes will be written to
the end of the file rather than the beginning. A new FileDescriptor
object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called
with name as its argument.
If the file exists but is a directory rather than a regular file, does
not exist but cannot be created, or cannot be opened for any other
reason then a FileNotFoundException is thrown.
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or
cannot be opened for any other reason.
SecurityException - if a security manager exists and its checkWrite method denies write access to the file. Since:
JDK1.1 See Also:
SecurityManager.checkWrite(java.lang.String)
So change
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file));
to
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file, true));

Unable to write to external SD Card in Android

I am trying to write files in the external SD card folder. Even after having set the required permission in the manifest file, I am unable to write on the external SD card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code:
String path = "/mnt/extsd/nit.txt";
File myFile = new File(path);
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
}
try {
FileOutputStream fostream = new FileOutputStream(myFile);
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
bwriter.write("Hi welcome ");
bwriter.newLine();
bwriter.close();
oswriter.close();
fostream.close();
txtText.setText("success");
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
On the other hand when I use ES File Explorer and try to create a file, it creates it without any issues.
Don't use the absolute path String path = "/mnt/extsd/nit.txt"; because you never know about android device being used by users. Rather you can get the external storage directory path by using Environment.getExternalStorageDirectory().toString().
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
File log = new File(Environment.getExternalStorageDirectory(), "your_file_name.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write("any data");
} catch (Exception e) {
}
And don't forget to close the streams.
First check sd-card is available or not.
String state = Environment.getExternalStorageState();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File folder = folder = new File(extStorageDirectory, "FolderName");
if(!folder.exists())
{
folder.mkdir();//making folder
}
File file = new File(folder,"Filename");//making file
}
Please try this code, it work in my application.

it works fine on desktop, but not on android. why?

saving socres to highscore.sav file, it works fine on desktop, but not on android. why?
String fileName = "highScores.sav";
file = new File(fileName);
public static void save(){
try{
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(gd);
out.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
Gdx.app.exit();
}
}
public static void load(){
try{
if(!saveFileExists()){
init();
return;
}
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
gd = (GameData) in.readObject();
in.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
Gdx.app.exit();
}
}
got error: java.io.FileNotFoundException: /highScores.sav: open failed: EROFS (Read-only file system)
This isn't working because you have not specified a directory to save into. Android has tight restrictions on where an app can write files.
You don't need any permissions to read or write a file to internal memory. But you do need to specify internal memory (called local memory in libgdx).
Libgdx already handles this directly for you so you don't need to differentiate between desktop and Android. This explains exactly how to do it. All you need is the string or bytes you want to write into the file, and the libgdx API's handle the rest.
FileHandle file = Gdx.files.local(filename);
file.writeString(stringToWrite, false);
If you want to continue using your method of writing the file, you can get the path to the file like this:
String fileName = "highScores.sav";
file = new File(Gdx.files.getLocalStoragePath () + "/" + fileName);
Have you added the permission to the android app to allow writing to the storage space?

Categories

Resources