Appending to text file in android - java

I am trying to append to a text file that starts off empty and every time the method addStudent() is called it would add a student.toString() line to the said file. I don't seem to get any exceptions but for some reason, after the method call, the file remains empty. Here is my code.
public void addStudent() {
Student student = new Student();
EditText fName = findViewById(R.id.first_name);
EditText lName = findViewById(R.id.last_name);
EditText studentGpa = findViewById(R.id.gpa);
String firstName = String.valueOf(fName.getText());
String lastName = String.valueOf(lName.getText());
String gpa = String.valueOf(studentGpa.getText());
if(firstName.matches("") || lastName.matches("") || gpa.matches("")) {
Toast.makeText(this, "Please make sure none of the fields are empty", Toast.LENGTH_SHORT).show();
} else {
double gpaValue = Double.parseDouble(gpa);
student.setFirstName(firstName);
student.setLastName(lastName);
student.setGpa(gpaValue);
try {
FileOutputStream fos = openFileOutput("students.txt", MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(student.toString());
osw.flush();
osw.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What might be the problem here? The file students.txt itself is located in assets folder

The problem may be with the fact that 'assets' directory doesnt exists on phone. So if I understand you correctly you may checking the wrong file.

What might be the problem here? The file students.txt itself is located in assets folder.
If it is in the assets folder then you should use AssetsManager top open an input stream to it. Files in the assets folder are readonly so trying to write to them does not make sense.
FileOutputStream fos = openFileOutput("students.txt", MODE_APPEND);
That wil create a file in private internal memory of your app. The code looks ok. But it makes no sense trying to find the file on your phone with a file manager or other app as as said that is private internal memory of your app only.
You use a relative path with "studends.txt" and now you do not know where the file resides.
Well the file resides in the path indicated by getFilesDir().
You could as well have used a full path with
File file = new File(getFilesDir(), "students.txt");
and then open a FileOutputStream with
FileOutputStream fos = new FileOutputStream(file);

Related

Android Internal File

I have created a file using FileOutputStream in my app,
fos = this.openFileOutput("foo.txt", Context.MODE_PRIVATE);
Now, I want to check if the file exists, using
File file = new File("foo.txt");
if (file.exists()) {
file.delete();
Log.d("tag", "im here");
}
If the file exists I want to delete it. But my code does not seem to reach "im here". Is my approach wrong? How can I correct it? Thanks
You need to specify the directory in which to look for the file. This can be achieved through the getFilesDir() method.
File file = new File(getFilesDir(), "foo.txt");
if (file.exists()) {
file.delete();
Log.d("tag", "im here");
}

What folder should I store text files?

I have my classes in /src/com.example.myapp/ and I have a text mytext.txt there too.
However, when I reference static File f = new File("mytext.txt")); it does not find it, even though the file is in the same directory as the class.
What do I need to do? What directory is it actually looking in?
Assets is read-only. I need somewhere where I can read and update the text file.
Use an assets folder.
Here is an example...
Loading array from a text file in assets folder (Android)
You create the assets folder in your root project folder then place your file in it. Once it's there, you access this way:
getAssets().open("file.txt");
the getAssets method is part of your Activity / Context. Context carriers a lot of the information about your app.
If you are not in an Activity, you can pass the Context to your class and use this:
context.getAssets().open("file.txt");
If you want the file with EDIT mode, you can use Internal/External Storage
Then you can read it as:
String filePath = context.getFilesDir().getAbsolutePath(); //returns current directory.
File file = new File(filePath, fileName);
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.
You can even write to this file :
String filename = "myfile";
String string = "ur data";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Hope it will help you ツ
Use the assets directory:
assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

How to write file to sd-card? (Android) No errors, but nothing written

I'm new to developing android apps. And already overchallenged with my first project. My app should be able to save a list of EditText fields to a text file by clicking a "save"-Button.
But I got no success to write a file to my SD-card.
My code:
(function in MainActivity.java called by the button)
public void saveData(View view){
try{
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/myapp/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "datei.txt");
FileOutputStream os = new FileOutputStream(file);
String data = "some string";
os.write(data.getBytes());
os.flush();
os.close();
}
catch (IOException e){
Log.e("com.sarbot.FitLogAlpha", "Cant find Data.");
}
}
With Google I found another way:
public void saveData3(View view){
FileWriter fWriter;
File sdCardFile = new File(Environment.getExternalStorageDirectory() + "/datafile.txt");
Log.d("TAG", sdCardFile.getPath()); //<-- check the log to make sure the path is correct.
try{
fWriter = new FileWriter(sdCardFile, true);
fWriter.write("CONTENT CONTENT UND SO");
fWriter.flush();
fWriter.close();
}catch(Exception e){
e.printStackTrace();
}
}
In my manifest.xml I set the permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
And the function from developer guide returns me True -> SD-card is writable.
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
In the res/layout/activity_main.xml are some TextViews and EditText and a save button with android:onClick="saveData" argument. The function is called. The SD-card is writable. And no IO errors. But after pressing the button (without error) there is still no new file on my SD-card. I already tried to create the file manually and just append but nothing changed. I tried some other function with BufferedWriter too .. but no success.
I'm running my Sony Xperia E with USB-Debug mode. Unmount and mounted the SD-card on my PC but cant find the file. Maybe it is only visible for the phone? It doesn't exist? I don't know what to do because I get no errors. I need the content of this file on my computer for calculations.
:EDIT:
The problem was not in the code.. just in the place I looked up. The externalStorage -> sdCard seems to be the internal and the removable sdcard is the -> ext_card.
After this line,
File file = new File(dir, "datei.txt");
Add this code
if ( !file.exists() )
{
file.createNewFile(); // This line will create new blank line.
}
os.flush() is missing in your code. Add this snippet before os.close()

Java: create temp file and replace with original

i need some help with creating file
Im trying in the last hours to work with RandomAccessFile and try to achieve the next logic:
getting a file object
creating a temporary file with similar name (how do i make sure the temp file will be created in same place as the given original one?)
write to this file
replace the original file on the disk with the temporary one (should be in original filename).
I look for a simple code who does that preferring with RandomAccessFile
I just don't how to solve these few steps right..
edited:
Okay so ive attachted this part of code
my problem is that i can't understand what should be the right steps..
the file isn't being created and i don't know how to do that "switch"
File tempFile = null;
String[] fileArray = null;
RandomAccessFile rafTemp = null;
try {
fileArray = FileTools.splitFileNameAndExtension(this.file);
tempFile = File.createTempFile(fileArray[0], "." + fileArray[1],
this.file); // also tried in the 3rd parameter this.file.getParentFile() still not working.
rafTemp = new RandomAccessFile(tempFile, "rw");
rafTemp.writeBytes("temp file content");
tempFile.renameTo(this.file);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
rafTemp.close();
}
try {
// Create temp file.
File temp = File.createTempFile("TempFileName", ".tmp", new File("/"));
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("Some temp file content");
out.close();
// Original file
File orig = new File("/orig.txt");
// Copy the contents from temp to original file
FileChannel src = new FileInputStream(temp).getChannel();
FileChannel dest = new FileOutputStream(orig).getChannel();
dest.transferFrom(src, 0, src.size());
} catch (IOException e) { // Handle exceptions here}
you can direct overwrite file. or do following
create file in same directory with diff name
delete old file
rename new file

Creating a file is causing problem, the File.getPath() doesn't seem to work

I am trying to create a back up file for an html file on a web server.
I want the backup to be in the same location as the existing file (it's a quick fix). I want to create the file using File file = new File(PathName);
public void backUpOldPage(String oldContent) throws IOException{
// this.uri is a class variable with the path of the file to be backed up
String fileName = new File(this.uri).getName();
String pathName = new File(this.uri).getPath();
System.out.println(pathName);
String bckPath = pathName+"\\"+bckName;
FileOutputStream fout;
try
{
// Open an output stream
fout = new FileOutputStream (bckFile);
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
But if instead I was to set bckPath like this, it will work.
String bckPath = "C://dev/server/tomcat6/webapps/sample-site/index_sdjf---sd.html";
I am working on Windows, not sure if that makes a difference.
The result of String bckPath = pathName+"\"+bckName;
is bckPath = C:\dev\server\tomcat6\webapps\sample-site\filename.html - this doesn't result in a new file.
Use File.pathSeparator, that way you dont need to worry what OS you are using.
Try to use File.getCanonicalPath() instead of plain getPath(). This helps if the orginal path is not fully specified.
Regarding slashes, / or \ or File.pathSeparator is not causing the problem, because they are all the same on Windows and Java. (And you do not define bckFile in your code, only bckPath. Also use getCanonicalPath() on the new created bckPath.)

Categories

Resources