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.
Related
Honestly, I've searched a lot do this task so I ended up trying various methods but nothing worked until I ended up on this code. It works for me perfectly like it should, so I do not want to change my code.
The help I need is to put this code in a such a way that it begins to read a file, but if it the file doesn't exist then it will create a new file.
Code for saving data:
String data = sharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Code for loading data:
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte [fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So If I add the saving data code in to the "FileNotFoundException" catch of the loading data part then could I achieve what I want?
Add
File file = new File(FILENAME);
if(!file.exists())
{
file.createNewFile()
// write code for saving data to the file
}
above
fis = openFileInput(FILENAME);
This will check if there exists a File for the given FILENAME and if it doesn't it will create a new one.
If you're working on Android, why don't you use the API's solution for saving files?
Quoting:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
You should really read the whole document, they explain pretty well the basic ways of creating or accessing files, you can also check the different ways of storing data.
But regarding your original question:
So If I add the saving data code in to the "FileNotFoundException"
catch of the loading data part then could I achieve what I want?
Yes, you could achieve it.
Try this one:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile()){
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try {
// ...
// read data
// ...
}finally{
r.close();
}
}
Ref: Java read a file, if it doesn't exist create it
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.
OKay so I'm handling Files where I ask user Input and my program updates the Spinner with new selection.
Here's the codes for write:
public void writeOnFile(String string){
try {
FileOutputStream file = openFileOutput(fileName, Context.MODE_APPEND);
file.write(string.getBytes());
file.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and read:
public void readOnFile(){
try {
FileInputStream file = openFileInput(fileName);
if(file!=null){
InputStreamReader inputreader = new InputStreamReader(file);
BufferedReader buffreader = new BufferedReader(inputreader);
String course;
while((course = buffreader.readLine()) != null){
adapter.add(course);
}
}
file.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and here's bit of my spinner's code:
courseSpinner = (Spinner) findViewById(R.id.courseSpinner);
adapter = new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
readOnFile();
adapter.add("The Country Club");
courseSpinner.setAdapter(adapter);
When I update the Spinner instead of seeing two selections which is "course 1" and "course" 2
I see one selection with the text "course 1course 2" :/
How do I fix this?
Since you are interpreting the strings as separated by newline, you need to write each of the strings to new line in the file.
Change your write code to:
public void writeOnFile(String string){
try {
FileOutputStream file = openFileOutput(fileName, Context.MODE_APPEND);
file.write(string.getBytes());
file.write("\n".getBytes());
file.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its not present in the path data/data/package-name/file name.txt & it didn't display the content on emulator.
My code is..
public class PhonememAct extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=(TextView)findViewById(R.id.tv);
FileOutputStream fos = null;
try {
fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fos.write("Hai..".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = openFileInput("Test.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int c;
try {
while((c=fis.read())!=-1)
{
tv.setText(c);
setContentView(tv);
//k += (char)c;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in adv.
You don't need to use input/output streams if you are simply trying to write/read text.
Use FileWriter to write text to a file and BufferedReader to read text from a file - it's much simpler. This works perfectly...
try {
File myDir = new File(getFilesDir().getAbsolutePath());
String s = "";
FileWriter fw = new FileWriter(myDir + "/Test.txt");
fw.write("Hello World");
fw.close();
BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt"));
s = br.readLine();
// Set TextView text here using tv.setText(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
//To read file from internal phone memory
//get your application context:
Context context = getApplicationContext();
filePath = context.getFilesDir().getAbsolutePath();
File file = new File(filePath, fileName);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString(); //the output text from file.
This may not be an answer to your question.
I think, you need to use the try-catch correctly.
Imagine openFileInput() call fails, and next you are calling fos.write() and fos.close() on a null object.
Same thing is seen later in fis.read() and fis.close().
You need to include openFileInput(), fos.write() and fos.close() in one single try-catch block. Similar change is required for 'fis' as well.
Try this first!
You could try it with a stream.
public static void persistAll(Context ctx, List<myObject> myObjects) {
// save data to file
FileOutputStream out = null;
try {
out = ctx.openFileOutput("file.obj",
Context.MODE_PRIVATE);
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(myObjects);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is working fine for me like this. Saving as text shouldn't be that different, but I don't have a Java IDE to test here at work.
Hope this helps!