Error in adding text to existing txt file - android

Firstly, i know there are same questions in this web site but i couldn't add text to my existing txt file. maybe i miss out something but where ? anyway here are my codes.
i have translate.txt file. it is /raw folder.and When i click the button, the words which are written in the editTexts(w1,w2) must be added to the existing translate.txt file.But it is not working..
public class Add extends Activity {
EditText w1,w2;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
w1=(EditText)findViewById(R.id.idText1);
w2=(EditText)findViewById(R.id.idText2);
save=(Button) findViewById(R.id.idSave);
save.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String word1=w1.getText().toString();
String word2=w2.getText().toString();
writefile(word1,word2);
}
});
}
public void writefile(String word1,String word2)
{
try
{
String finalstring=new String(word1 + " " + word2);
FileOutputStream fOut = openFileOutput("translate.txt",MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(finalstring);
osw.flush();
osw.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
} catch(Exception e)
{
Toast.makeText(this, "ERROR!!!", Toast.LENGTH_SHORT).show();
}
}
}

A) Code to write APPEND file in Android
public void writefile(String word1,String word2)
try {
String path = sdCard.getAbsolutePath() + "/";
File logFile = new File(path + "translate.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append(word1 + " " + word2);
buf.newLine();
buf.flush();
}
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
B) Rule/ Permission
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT For user
You cannot write a file to raw folder. Its read-only. Precisely you can't modify anything contained within "Res" folder on the fly.
Check this out, https://stackoverflow.com/a/3374149

Just in case you don't want to store the data in sd card and want to use the previous method
the way you was creating a file and stroing data to it was not actually editing the file in res/ raw folder ( because it can not be edited )
but the data you was writing was actually stored in a private file associated with this Context's application package for reading.
hence it was there and the file can be read as follow:
private void readFile() {
// TODO Auto-generated method stub
try {
FileInputStream fin = openFileInput("translate.txt");
InputStreamReader isr = new InputStreamReader(fin);
BufferedReader br = new BufferedReader(isr);
String str;
StringBuilder str2 = new StringBuilder();
while ((str = br.readLine()) != null) {
str2 = str2.append(str);
}
isr.close();
editText.setText(str2.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you can follow this method incase you dont want to store file in sd card because files in sd crad can be read by anyone.

Related

Write and read a file in the internal storage (not in the app package)

I would like to create and read a file in the internal storage (not SD card) but I want a file accessible for the user in the Explorer.
How can I do ?
My code :
public void WriteFile(View v) {
try {
FileOutputStream fileout= getActivity().openFileOutput("password.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("hello");
outputWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ReadFile(View v) {
try {
FileInputStream fileIn=getActivity().openFileInput("hello.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getActivity(), s + " ",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
I found the solution using MODE_WORLD_READABLE instead of MODE_PRIVATE.

Android save to file.txt appending

I admittedly am still learning and would consider myself a novice (at best) regarding programming. I am having trouble with appending a file in android. Whenever I save, it will rewrite over the file, and I am having trouble understanding how to keep the file that is already there and only add a new line. Hoping for some clarity/advice. Here is how I am saving to the file (which rewrites the file each time I save).
public void saveText(View view){
try {
//open file for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
//write information to file
EditText text = (EditText)findViewById(R.id.editText1);
String text2 = text.getText().toString();
out.write(text2);
out.write('\n');
//close file
out.close();
Toast.makeText(this,"Text Saved",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
//if caught
Toast.makeText(this, "Text Could not be added",Toast.LENGTH_LONG).show();
}
}
Change this,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
to,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
This will append your new contents to the already existing file.
I Hope it helps!
Use this method, pass filename and the value to be added in the file
public void writeFile(String mValue) {
try {
String filename = Environment.getExternalStorageDirectory()
.getAbsolutePath() + mFileName;
FileWriter fw = new FileWriter("ENTER_YOUR_FILENAME", true);
fw.write(mValue + "\n\n");
fw.close();
} catch (IOException ioe) {
}
}
To display the content of the saved file with the line breaks with a button click use:
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(fileTitle);
int c;
String temp = "";
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
To Delete content of existing file whist retaining the filename you can use:
deleteOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_PRIVATE);
// fOut.write(data.getBytes());
dataTitle = "";
fOut.write(data.getBytes());
fOut.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This worked for me. Takes content of a TextEdit called textTitle. Writes it to file called dataTitle. Then writes a new line with fOut.write("\n"). The next text entered into TextEdit is added to the file with a line break.
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_APPEND);
fOut.write(dataTitle.getBytes());
fOut.write('\n');
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Create txt file, write and read from it Android

I need when app starts, to check if file exists, if not to be created..
I need a block of code to append files into it
than I need a block of code that read that text line by line
than to remove a line ....
I found this code at stackoverflow, and they said that the file will be created in that location...
//Here I have this :
//Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead
//
String filePath = "/data/data/com.example.myapp/files/text.txt";
File file = new File(filePath);
if(file.exists()){
//Do nothing
}
else{
try {
final String TESTSTRING = new String("");
FileOutputStream fOut = openFileOutput("text.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(TESTSTRING);
osw.flush();
osw.close();
} catch (IOException ioe)
{ioe.printStackTrace();}
}
}
To add Lines in text I made this :
private void write(){
S ="/data/data/com.example.myapp/files/text.txt";
try {
writer = new FileWriter(S, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.write(emri.getText().toString() + "\n" + link.getText().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And when I have to read them :
public class PlayList extends ListActivity {
ArrayList<String> listaE = new ArrayList<String>();
ArrayList<String> listaL = new ArrayList<String>();
InputStream instream;
int resh=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lexo();
String[] mStringArray = new String[listaE.size()];
mStringArray = listaE.toArray(mStringArray);
setListAdapter(new ArrayAdapter<String>(PlayList.this,android.R.layout.simple_list_item_1,mStringArray));
}
private void lexo(){
String S ="/data/data/com.example.myapp/files/text.txt";
try {
// open the file for reading
instream = new FileInputStream(S);
// if file the available for reading
if (instream != null) {
// 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
do {
line = buffreader.readLine();
if ((resh % 2) == 0) {
listaL.add(line);
}
else {
listaE.add(line);
}
// do something with the line
} while (line != null);
}
} catch (Exception ex) {
// print stack trace.
} finally {
// close the file.
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My code does not work at all, and is missing the code to remove a line..
So everything I need is :
Code to write into file ( file to be saved because will be used until the app will be installed )
Code to read that file line by line ( so to be added in array, odd lines in one array, other lines in another array )
Code to remove a line from that file ( array to be added in listview and when user touches the line, touched line to be removed )
To add lines on list-activity
Any help will be very very appreciated,
Thanks...
First of all, you should use .getFilesDir().getPath() on your app's context, instead of hardcoding the path. That's commented in your first block. Second, create an OutputStream like this:
OutputStream out = new FileOutputStream(filePath);
If you have an InputStream called in, you'll be able to write it to a file using this code:
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
in.close();
out.close();
When you do create a file, check the rest (I didn't look) and get back to StackOverlow, if it fails. Don't make any of us do all the work, okay? Rip it to small part and make an effort.
Good luck with your work.

I can create file but can't write to it

Could someone look at this snippet of code please and let me know what I'm doing wrong? It's a simple function that takes a string as parameter which it uses as a file name, adding ".txt" to the end of it.
The function checks if the file exists, creating it if it doesn't and then writes two lines of text to the file. Everything appears to be working and the file is created successfully on the sd card. However, after everything is done, the file is empty (and has a size of 0 bytes).
I suspect it's something obvious that I'm overlooking.
public void writeFile(String fileName) {
String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
myPath.mkdirs();
File file = new File(myPath, fileName+".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
return;
}
}
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
// Do whatever
}
}
Hi I will show you the full code I use, works perfect.
I don't use
new OutputStreamWriter()
i use
new BufferedWriter()
here is my Snippet
public void writeToFile(Context context, String fileName, String data) {
Writer mwriter;
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");
if (!dir.isDirectory()) {
dir.mkdir();
}
try {
if (!dir.isDirectory()) {
throw new IOException(
"Unable to create directory myFolder. SD card mounted?");
}
File outputFile = new File(dir, fileName);
mwriter = new BufferedWriter(new FileWriter(outputFile));
mwriter.write(data); // DATA WRITE TO FILE
Toast.makeText(context.getApplicationContext(),
"successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
mwriter.close();
} catch (IOException e) {
Log.w("write log", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
}
}
-- Original Code --
That one took a while to find out. The javadocs
here brought me on the right track.
It says:
Parameters
name The name of the file to open; can not contain path separators.
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
The file is created, if it does not exist, but it is created in the private app space. You create the file somewhere on the sd card using File.createNewFile() but when you do context.openFileOutput() it creates always a private file in the private App space.
EDIT: Here's my code. I've expanded your method by writing and reading the lines and print what I got to logcat.
<pre>
public void writeFile(String fileName) {
try {
OutputStreamWriter writer = new OutputStreamWriter(
getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
// Now read the file
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(
getContext().openFileInput(fileName + ".txt")));
for(String line = is.readLine(); line != null; line = is.readLine())
Log.d("STACKOVERFLOW", line);
is.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
}
Change the mode from Context.MODE_PRIVATE to Context.MODE_APPEND in openFileOutput()
MODE_APPEND
MODE_PRIVATE
Instead of
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
Use
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
UPDATE :
1.
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
OutputStreamWriter writer = new OutputStreamWriter(osr);
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write("First line");
fbw.newLine();
fbw.write("Second line");
fbw.newLine();
fbw.close();
Or 2.
private void writeFileToInternalStorage() {
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
String eol = System.getProperty("line.separator");
BufferedWriter fbw = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(osr);
fbw = new BufferedWriter(writer);
fbw.write("First line" + eol);
fbw.write("Second line" + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fbw != null) {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

When i move a file from raw folder to SD card in android, the file won't move

I used the following code to move the audio file form res/raw folder to SD card, when i execute this code, the file won't move. why it will happens, in which line i made mistake.
MoveAudio.java
public class MoveAudioextends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button a = (Button) findViewById(R.id.Button01);
a.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
byte[] buffer = null;
InputStream fIn = getBaseContext().getResources()
.openRawResource(R.raw.song);
int size = 0;
System.out.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + fIn);
try {
size = fIn.available();
System.out
.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + size);
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
String path = "/sdcard/media/audio/ringtones/";
String filename = "examplefile" + ".ogg";
boolean exists = (new File(path)).exists();
if (!exists) {
System.out
.println("<<<<<<<FALSE SO INSIDE THE CONDITION>>>>>>>>>>>>>>>>>>>>");
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path + filename);
System.out
.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + save);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://" + path + filename)));
File k = new File(path, filename);
System.out.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + k);
}
});
}
}
In my xml file i had sing button, when i click that button the file will move. This code executes without error but the file won't move.
Instead of having empty catch blocks, try instead to write those out.
e.printStackTrace();
// I believe it is.
Additionally, have you permissions to write to the SD Card?
permission.WRITE_EXTERNAL_STORAGE
What is the filename of the song in your resource folder? The reason i ask is that there is a max file size that can be read back for a file that is compressed. Your file, if named with a .ogg extension shouldn't be compressed and thus not constrained to this limit. However if you named it something else that gets compressed it may have this problem.
A good way to log errors is to use androids Log methods. Do so like this:
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e(TAG, "FileNotFoundException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException", e);
}
You may be getting a "Data exceeds UNCOMPRESS_DATA_MAX (1290892 vs 1048576)" message.
The only way to tell for sure though is to log your error. It is also possible the SD card is out of space or you don't have permissions to write to it.
In this example, my raw file is "test.pdf"
We will use "Download" folder in our phone.
"test.pdf" in raw folder will be moved to "Download/test_filemove" folder as "example.pdf"
Make the new "raw" folder in "res" folder.
Copy "test.pdf" to "raw" folder.
Surely you should make Button01 in your layout.
Don't forget to give permission in your manifest file as below
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
I just modify your example a little bit.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.Button01);
a.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
byte[] buffer = null;
InputStream fIn = getBaseContext().getResources()
.openRawResource(R.raw.test);
int size = 0;
System.out.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + fIn);
try {
size = fIn.available();
System.out
.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + size);
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/test_filemove/";
String filename = "example" + ".pdf";
boolean exists = (new File(path)).exists();
if (!exists) {
System.out
.println("<<<<<<<FALSE SO INSIDE THE CONDITION>>>>>>>>>>>>>>>>>>>>");
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
System.out
.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + save);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
I hope this help you out.

Categories

Resources