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();
}
}
});
Related
I am currently making a journal app, so the users type their entry into an EditText and it saves in their phone and they can load it up later. At first I used just getFilesDir() but recently there is this weird rList file that shows up every time I open the app and I couldn't figure it out(I wrote a question about it). So now I want to save these files in this specific directory called TextEntries
Here is the code for my save funcction:
public void save(View v) {
textFile = inputTitle.getText().toString();
String text = inputFeelings.getText().toString();
FileOutputStream fos = null;
try {
String rootPath = getFilesDir().getAbsolutePath() + "/TextEntries/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
fos = openFileOutput(textFile, MODE_PRIVATE);
fos.write(text.getBytes());
inputFeelings.getText().clear();
Toast.makeText(this, "Saved to " + getFilesDir() + "/TextEntries/" + textFile,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
All help is welcome and thank you in advance.
replace
openFileOutput(textFile, MODE_PRIVATE);
with
new FileOutputStream(rootPath + textFile)
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.
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.
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.
I am really facing problem from last couple of days but I am not able to find the exact solution please help me.
I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with SequenceInputStream or byte array but I am not able to get exact result please help me.
My code is the following:
public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/final.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audNames = new ArrayList<String>();
String file1 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/one.mp3";
String file2 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/two.mp3";
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/" + "final.mp3");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
audNames.add(file1);
audNames.add(file2);
Button btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createCombineRecFile();
}
});
}
public void createCombineRecFile() {
// String combined_file_stored_path = // File path in String to store
// recorded audio
try {
fos = new FileOutputStream(combined_file_stored_path, true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
File f = new File(audNames.get(0));
File f1 = new File(audNames.get(1));
Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());
fileContent = new byte[(int) f.length()];
ins = new FileInputStream(audNames.get(0));
int r = ins.read(fileContent);// Reads the file content as byte
fileContent1 = new byte[(int) f1.length()];
ins1 = new FileInputStream(audNames.get(1));
int r1 = ins1.read(fileContent1);// Reads the file content as byte
// from the list.
Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);
//fos.write(fileContent1);// Write the byte into the combine file.
byte[] combined = new byte[fileContent.length + fileContent1.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
}
fos.write(combined);
//fos.write(fileContent1);*
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Log.v("Record Message", "===== Combine File Closed =====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already published an app with this function... try my method using SequenceInputStream, in my app I just merge 17 MP3 files in one and play it using the JNI Library MPG123, but I tested the file using MediaPlayer without problems.
This code isn't the best, but it works...
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mp3 files are some frames.
You can concatenate these files by appending the streams to each other if and only if the bit rate and sample rate of your files are same.
If not, the first file plays because it has truly true encoding but the second file can not decode to an true mp3 file.
Suggestion: convert your files with some specific bit rate and sample rate, then use your function.