I have written simple code to save data into text files internally. But, after running the code, I don't know where I can find the required file. Additionally, I find an error message in the log cast as
"SPAN_EXCLUSIVE_EXCLUSIVE"
package com.example.saving_files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
File file;
FileOutputStream fos;
String FlieName = "output.text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file = new File(FlieName);
try {
fos = openFileOutput(FlieName, MODE_PRIVATE);
fos.write(122);
} catch (FileNotFoundException e) {
Log.d("output", file.getAbsolutePath());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
file = getFilesDir();
Log.d("output_path", file.getAbsolutePath());
}
}
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, "filename");
FileOutputStream f = new FileOutputStream(file);
This code will create new file in the root directory of your SD. Dont forget to add
<uses-permission> to write to SD in your manifest
Check this code and comments;
File sdcard = Environment.getExternalStorageDirectory();
File f = new File(sdcard, "/yourfile");
if (!f.exsist()) {
f.createNewFile();
// Use outwriter here, (outputstream) search how to write into a text file in java code
}
Related
Here's a code of MainActivity.java to save a file named filename.txt in App's Internal Storage, which is working fine.
package com.bla.smthing;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am able to see the file by File Explorer of Android Studio. How can I save the file in a directory say files/Somefolder/otherfolderchild/filename.txt?
Currently, it is saving as files/filename.txt
Do I need to create additional parent file directories for that?
Try this it might help you. For the above marshmallow version please check the write permissions.
public void saveToExternalStorage() {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/directoryName";
try
{
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, "fileName.txt");
if(file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
fOut.flush();
fOut.close();
}
catch (Exception e)
{
Log.e("saveToExternalStorage()", e.getMessage());
}
}
I Downloaded both jars from http://www.siegmann.nl/epublib/android
but the sample code does not create a file
in my sdcard or internal storage
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import nl.siegmann.epublib.domain.Author;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.epub.EpubWriter;
import android.app.Activity;
import android.os.Bundle;
public class EpubAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Book b = new Book();
b.getMetadata().addTitle("test epub book");
b.getMetadata().addAuthor(new Author("author name"));
EpubWriter w = new EpubWriter();
FileOutputStream fos;
try {
File file = new File(getApplicationContext().getExternalFilesDir(null), "test.epub");
if(!file.exists()){
file.createNewFile();
}
fos = new FileOutputStream(file);
w.write(b, fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
not get error however I can not find the file (it is not created)
I forgot to add
<uses-permission android: name = "android.permission.WRITE_EXTERNAL_STORAGE" />
in Android Manifest
Here is my source code;
I've installed microsdsvc app on the external_SD.
szSDCardFileName = "/storage/external_SD/Android/data/com.tmnt.microsdsvc/files/AAA.DAT";
if ((fp = open(szSDCardFileName, O_RDWR|O_DIRECT|O_SYNC, S_IRWXU)) == -1) {
if ((fp = open(szSDCardFileName, O_RDWR|O_DIRECT|O_SYNC|O_CREAT, S_IRWXU)) == -1) {
return -1;
}
}
memset(g_buf, 0x00, BLOCK_LENGTH);
if (read(fp, (char *)g_buf, BLOCK_LENGTH) == ERROR) {
__android_log_print(ANDROID_LOG_INFO, "JNI", "<Err>file read error[errno=%d, handle=%d]", errno, fp);
return -1;
}
when running the code on the Lg G2 Kitkat version, open() is OK, but next read() is failed with errorno 22.
I don't know that what I mistake!!
Maybe this is the reason why...
KitKat, applications will no longer be able to create, modify, or remove files and folders on 'secondary external storage device' respectively dual-storage devices with internal flash AND a removable / external SD card.
"The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions."
http://source.android.com/devices/tech/storage/index.html
package com.example.readfilefromexternalresource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
BufferedReader reader = null;
try {
Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
File file = Environment.getExternalStorageDirectory();
File file2 = new File(file.getAbsolutePath()+File.separator + "myText.txt");
reader = new BufferedReader(new FileReader(file2));
StringBuilder textBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
textView.setText(textBuilder);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
First you need to get the state of your external sd card
then you check if there is a mounted sd card, if no sd card its found, it will do nothing(you can put error msgs here)
get its absolute path and add a separator then put the file name of the file you want to read
use a BufferedReader to read your textFile.
Use a StringBuilder to build your string, it is more efficient than simple concatinating strings
after appending your strings, always close the reader to save memory, smartphones are known to have less memory than desktop
call to toString() method of the StringBuiler to create your String which you can use
String state = Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED)) {
} else {
File externalDir = Environment.getExternalStorageDirectory();
File textFile = new File(externalDir.getAbsolutePath()
+ File.separator + fileName);
BufferedReader reader
= new BufferedReader(new FileReader(textFile));
StringBuilder textBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
reader.close();
String yourString = textBuilder.toString();
}
it throws a FileNotFound exception btw. You can do the same in writing a file.
Can I change the contrast of an image from the byte stream of the Image? I have done necessary to do copying the image and I need to add the change contrast part to the code.
Any idea how to do this? Or is it even possible?
package make.image.bw;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class MakeImageBWActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // set screen view
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath() +"/earthglobe.jpg";
RandomAccessFile file = null;
try {
file = new RandomAccessFile(imageInSD, "r");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
File myFile = new File(Environment.getExternalStorageDirectory(), "latestearth.jpg");
byte[] buffer = new byte[1024];
try {
FileOutputStream out = new FileOutputStream(myFile);
while(file.read(buffer)!=-1){
out.write(buffer,0,1024);
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("tag", "finished");
finish();
}
}
Thanking You in advance for your valuable suggestions.
You should try to look at that Google IO 2012 session : Doing More With Less: Being a Good Android Citizen
There is a good demo of image manipulation with RenderScript at 22min30.
The code of the presentation can be found here
here is my entire code (ps Im a noobie);
package xom.aaa.aaa;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FilewritertestActivity extends Activity {
TextView textout1, textout2, textout3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.button1);
textout1 = (TextView) findViewById(R.id.textView1);
textout2 = (TextView) findViewById(R.id.textView2);
textout3 = (TextView) findViewById(R.id.textView3);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//--------- OutputStreamWriter ------------
try {
FileOutputStreamfOut=openFileOutput("settings1.dat", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write( "using fileoutput stream to write this to a file");
osw.flush();
osw.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
String datax = "";
StringBuffer buffer = new StringBuffer();
//--------- InputStreamReader -------------------
try {
FileInputStream fIn = openFileInput("settings1.dat");
Reader reader = new InputStreamReader(fIn);
int data = reader.read(); // reads the next char
while(data != -1){
buffer.append((char)data);
data = reader.read();
}
reader.close();
} catch ( Exception e) {
e.printStackTrace();
}
textout1.setText( buffer.toString());
//--------------- FileWriter ---------------
try {
FileWriter fw = new FileWriter("settings1.dat");
BufferedWriter out = new BufferedWriter(fw);
//BufferedWriter out = new BufferedWriter(new FileWriter("settings1.dat"));
out.write("a String");
out.close();
} catch (Exception e){
e.printStackTrace();
textout2.setText(e.toString());
}
}
});
}
}
Problem is FileWriter Not working ( for file "settings1.dat")
but OutputStreamWriter and InputStreamReader does work ( for file "settings1.dat")
the code shows writing then reading to file "settings1.dat" Is ok with Stream Witer/Reader...
But FileWriter code get error message Filenotfoundexception "read-only file system"
So why does one technique work on the same File and the other doesn´t
Can you please tell what Iam missing -- thanks Trevor
I'm guessing your problem is you just aren't getting an IOException. You could try changing
catch(IOException e)
to
catch(Exception e)
This will then catch all exceptions which extend the Exception object (it will not catch Errors though). However, I don't have the tools to test out your code so you will have to try it out yourself and post the results.
Best of luck.