Android Internal File - java

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");
}

Related

Appending to text file in android

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);

Create file in jsp servlet

When I create a file in java servlet, I can't find that file for opening. This is my code in servlet:
FileOutputStream fout;
try {
fout = new FileOutputStream("title.txt");
new PrintStream(fout).println(request.getParameter("txttitle"));
fout.close();
System.out.println(request.getParameter("txttitle"));
} catch (Exception e) {
System.out.println("I can't create file!");
}
Where I can find that file?
if you create file first as in
File f = new File("title.txt");
fout = new FileOutputStream(f);
then you use getAbsolutePath to return the location of where it has been created
System.out.println (f.getAbsolutePath());
Since you have'nt specified any directory for the file, it will be placed in the default directory of the process that runs your servlet container.
I would recommand you to always specify the full path of your your file when doing this kind of things.
If you're running tomcat, you can use System.getProperty("catalina.base") to get the path of the tomcat base directory. This can sometimes help.
Create a file object and make sure the file exists:-
File f = new File("title.txt");
if(f.exists() && !f.isDirectory()) {
fout = new FileOutputStream(f);
new PrintStream(fout).println(request.getParameter("txttitle"));
fout.close();
System.out.println(request.getParameter("txttitle"));
}
If the servlet cannot find the file give the full path to the file specified, like new File("D:\\Newfolder\\title.txt");
you should check first if the file doesn't exist ,create it
if(!new File("title.txt").exists())
{
File myfile = new File("title.txt");
myfile.createNewFile();
}
then you can use FileWriter or FileOutputStream to write to the file i prefer FileWriter
FileWriter writer = new FileWriter("title.txt");
writer.write("No God But Allah");
writer.close();
simply simple

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()

File in local storage on Java, Android

I serialization object into new file in local storage by this mean:
ObjectOutputStream output=new ObjectOutputStream(openFileOutput("settings.dat", Context.MODE_PRIVATE));
output.writeObject(this);
output.close();
But in another function I must check file for exist:
File file=new File("settings.dat");
if (file.exists()) Toast.makeText(this, "yes", Toast.LENGTH_LONG).show();
file.exists() returne false always. Help me please.
Use:
File file = new File(getFilesDir() + "/settings.dat");
http://developer.android.com/reference/android/content/Context.html#getFilesDir%28%29

Categories

Resources