Writing file in external storage crashes android app - java

I know of cours that here were some question about this, but I still can't find answer.
I need to write some text in external storage, but this code makes application crashed. Note that String dane is this text.
void zapis2 (String dane){
Context myContext = getApplicationContext();
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file, true);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(dane);
out.close();}catch (IOException e) {
}
}
Have you got any idea. I add permision in android manifest of course.

Try this:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/foldername");
dir.mkdirs();
File file = new File(dir, "filename.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(dane); //your string which you want to store
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Hope this helps!

Contect.getExternalFilesDir(..) is only available from API8, if you run/deploy on earler versions it will crash.

Related

Write to File doesn't persist between activities

I'm writing and reading from a file and it works perfectly fine. However when the activity is switched or the app is closed it appears that the file is deleted or some such as null is returned when trying to read from the file. I believed it may be because I have an onCreate blank write to the file but that should only run upon the launch to make sure the file is created. I don't mind if the file doesn't persist between launches however it should at least persist between activities.
//in oncreate is writeToHistory("");
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void btnAnsClicked(View v) throws IOException {
File path = getApplicationContext().getFilesDir();
File file = new File(path,"JWCalcHistory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String oldAns = br.readLine();
if (!(oldAns.equals("null") || oldAns.equals(""))) {
if (Character.isDigit(readableSum.charAt(readableSum.length() - 1))) {
oldAns = "*" + oldAns;
}
UpdateSum(oldAns);
}
}
If someone can point out a way to make the contents of the file persist always until it is programmatically deleted or cleared then please let me know. The file doesn't already exist and is created upon the code being run.
You need to check if the file exists first. Something like this:
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
if(file.exists()) return;
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}

Unable to write to file - why?

I am attempting to save to long term file storage in android as well as create a new file in the process. This code keeps crashing with minimal helpful logcat.
Thanks.
public void save (String text) {
FileOutputStream fos = null;
try {
fos = openFileOutput("logfile.txt", MODE_PRIVATE);
fos.write(text.getBytes());
} catch (FileNotFoundException e)
{} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I expect it to create a file called logfile.txt and print text to it but instead it crashes.
Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:
// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);
The resulting path should be /data/data/tld.domain.package/files/logfile.txt.
file.getAbsolutePath() has the value.
See Save a file on internal storage.

Writing a text file to android storage for viewing later

So I'm trying to basically write some logs to a text file so i can view it later. I'm running this on a physical phone, not the emulator. I've tried so many different variations, and the most i got was it writing to data/data and storage/emulated but i can never access my file. Any help would be appreciated. Some of my latest undeleted examples have been:
String filename = "myfile.txt";
try {
File path = new File(context.getFilesDir(), "myfolder");
if (!path.exists())
path.mkdir();
File output = new File(path, filename);
BufferedWriter buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
Log.d("Success",
"Successfully wrote a file " + context.getFilesDir());
} catch (Exception e) {
e.printStackTrace();
}
and
final String appPath = String.format("%s/Datafiles",
context.getFilesDir());
File path = new File(appPath);
if (!path.exists()) {
path.mkdir();
}
String fileName = String.format("%s/filedemo.txt", appPath);
and
try {
String filename = "myfile.txt";
File path = new File(Environment.getRootDirectory(), "myfolder");
if (!path.exists())
path.mkdir();
File output = new File(path, filename);
BufferedWriter buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
Log.d("Success",
"Successfully wrote a file " + context.getFilesDir());
} catch (Exception e) {
e.printStackTrace();
}
Both of the following put it under /storage/emulated/0/Android/data/com.example.simplelte/files/system/stuff/test.txt
and
/storage/emulated/0/Android/data/com.example.simplelte/files/storage/emulated/0/stuff/test.txt
respectively
try {
File file = new File(context.getExternalFilesDir(Environment
.getRootDirectory().getCanonicalPath()), "stuff");
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
File output = new File(file, "test.txt");
BufferedWriter buff;
buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
buff.close();
Log.d("Success", output.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and
try {
File file = new File(context.getExternalFilesDir(Environment
.getExternalStorageDirectory().getCanonicalPath()),
"stuff");
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
File output = new File(file, "test.txt");
BufferedWriter buff;
buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
buff.close();
Log.d("Success", output.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and much more. I've followed every example I can think of. I literally just want to view the text file under Computer\Nexus 5\Internal storage\ I'm just a simple man with simple desires. Why does this have to be so complicated.
Have you tried this ?
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/");
File file = new File(dir, "text.txt");
FileOutputStream f = new FileOutputStream(file);

Android Java Read and Save data doesnt work

Hey I would like to save datas and then I would like to read them and put them in a EditText
speichern.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
save();
tv.setText("gespeichert");
}
});
private void save() {
try {
File myFile = new File("bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void read() {
int bla;
StringBuffer strInhalt = new StringBuffer("");
try {
FileInputStream in = openFileInput("bla.txt");
while( (bla = in.read()) != -1)
strInhalt.append((char)bla);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
What can i change?`
pelase help me
I'm usin eclipse
And i would like to safe the .txt not external.
I don't believe you are creating your file correctly:
File file = new File("test.txt");
file.createNewFile();
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write("Hello World");
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
And to read this file:
try {
// open the file for reading
InputStream instream = openFileInput("test.txt");
// if file the available for reading
if (instream) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine())) {
// do something with the settings from the file
}
}
// close the file again
instream.close();
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
}
And don't forget to encapsulate code with a try-catch block to catch an IOException which is thrown from these objects.
EDIT
Add this to your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
or...
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
Hope that helps! :)

OutputWriter Java or Android

I want to write data to an output file and save it on a mobile device or on a computer harddrive. I am able to get my code below to work, but have to create the directory in one step and then create the file in another. Is there a more effective way to code having to create an non-existing directory before writing a file there?
Thanks
StringBuilder Path = new StringBuilder();
Path.append(Environment.getExternalStorageDirectory().toString());
String filename = "test.txt";
String test_text = "Date, Item, Quantity, Description,";
File file = new File(Path.toString()+"/" +"Test Folder2/");
file.mkdirs();
FileOutputStream file_os = null;
try {
File file2 = new File(Path.toString()+"/" +"Test Folder2", filename);
file_os = new FileOutputStream(file2);
OutputStreamWriter osw = new OutputStreamWriter(file_os);
try {
osw.write(test_text);
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Toast.makeText(QuizSettingsActivity.this, Path.toString(),
Toast.LENGTH_LONG).show();
};
String FILENAME = "test";
String string = "Date, Item, Quantity, Description,";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
For more detail on saving file on external storage follow the link mentioned below:.http://developer.android.com/guide/topics/data/data-storage.html

Categories

Resources