Android: Can't find generated XML file - android

I am working on a method that writes an XML file to the device. I've allowed external storage in the manifest file, but I can't find the file at the location it should be.
Here is my code:
public static void write (){
Serializer serial = new Persister();
File sdcardFile = new File("/Prueba/file.xml");
Item respuestas = new Item();
try {
serial.write(respuestas, sdcardFile);
} catch (Exception e) {
// There is the possibility of error for a number of reasons. Handle this appropriately in your code
e.printStackTrace();
}
Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
}
}

Sdcard File path problem. Here is an exaple that write string in file.xml file.
File myFile = new File("/sdcard/file.xml");
try {
File myFile = new File("/sdcard/file.xml");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("encodedString");
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
You able to get External Storage name by this way,
String root = Environment.getExternalStorageDirectory().toString();

Related

FileNotFoundException although the text file exist (readable and writable)

I am trying to save data into text file in the internal storage and read it again .. It works fine in my mobile with android 11 but when i tried at android 8 it gives me this error
java.io.FileNotFoundException:/data/user/0/com.example.example/test.txt
(No such file or directory)
It appears at the first time to open the activity but i can clear it - as normal text - and write a new text and save it so the file is there and usable
here is read code
File path = getApplicationContext().getFilesDir();
File readFrom = new File(path, fileName);
byte[] content = new byte[(int) readFrom.length()];
try {
FileInputStream stream = new FileInputStream(readFrom);
stream.read(content);
return new String(content);
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
and this write code
public void writeToFile(String fileName, String content) {
File path = getApplicationContext().getFilesDir();
try {
FileOutputStream writer = new FileOutputStream(new File(path, fileName));
writer.write(content.getBytes());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

How can you save an audio file to external storage?

I have created a function to save the audio but don't know how to make it work. Would be nice if anybody would help me out?
private void saveAudio(int sound) {
String root = Environment.getExternalStorageDirectory().toString();
if (checkPermissionwrite()) { // check or ask permission
File myDir = new File(root, "/KangleiPdDrums/Sounds");
if (!myDir.exists()) {
myDir.mkdirs();
}
String fname = "Sound1.mp3";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile(); // if file already exists will do nothing
FileOutputStream out = new FileOutputStream(file);
out.write(sound);
out.flush();
out.close();
file.setReadable(true, false);
String pathed = file.getPath();
Toast.makeText(getApplicationContext(), "Saved at " + pathed, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Let me try to explain this
String root = Environment.getExternalStorageDirectory().toString();
In the root variable, he is getting the root reference of the private external storage.
if (checkPermissionwrite()) { }// check or ask permission
Here even this function is not available in your code but this function will use to take the write permission for the user
File myDir = new File(root, "/KangleiPdDrums/Sounds");
if (!myDir.exists()) {
myDir.mkdirs();
}
Here he is creating a directory or folder at the root folder of your external storage and then he is checking if this directory already exists or not if not then create the directory.
String fname = "Sound1.mp3";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
Here he storage the file name in the name folder and create the file and after that, he checked if the file already exists then delete this file.
try {
file.createNewFile(); // if file already exists will do nothing
FileOutputStream out = new FileOutputStream(file);
out.write(sound);
out.flush();
out.close();
file.setReadable(true, false);
String pathed = file.getPath();
Toast.makeText(getApplicationContext(), "Saved at " + pathed, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Here this code is used to write the file/audio at the directory that he created at the start and I think it's simple
Let me provide a link for the Indian and Pakistani users that understand Hindi or Urdu they can understand it through video as well
https://youtu.be/SZPF9KuPIV8

Where does the file get saved using "File file = new file(filename)" in Android

I am writing an android application. In the MainActivity.java, I created a method to write and then read contents from a file. These code runs successfully I and can store the data in a file named abc.txt, but I cannot find the written file in ES File Explorer.
public void writeInIt(View view) {
try {
String Message = editText.getText().toString();
final File myFile = new File("abc.txt");
if (!myFile.exists()) {myFile.createNewFile(); }
FileOutputStream outputStream = new FileOutputStream(myFile);
outputStream.write(Message.getBytes());
outputStream.close();
editText.setText("");
Toast.makeText(getApplicationContext(), "Message Saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Where does it save the file? Why I can't I search it through the File Explorer?
Ref to "http://developer.android.com/reference/java/io/File.html", if i include path, it will definitely store in that path location. However, if I not locate the dir, it can still store in device, but where does the file actually save???
"File file = new file(filename)"
this code does not save anything, it only cretes a class wrapper for file or director path. The closest method to actually create file would be to use file.createNewFile method.
There is guide for writing files from google: Saving Files
[edit]
following code generates exception "open failed: EROFS (Read-only file system)":
File fl = new File("test12.txt");
try {
fl.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
In Android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this is the code :
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
You can find this file in device manager.
Click your device (file symbol)
/data/user/0/com.example.myapplication/files and than follow this path

How to create files to a specific folder in android application?

In my application, I want to create a text file in the cache folder and first what I do is create a folder in the cache directory.
File myDir = new File(getCacheDir(), "MySecretFolder");
myDir.mkdir();
Then I want to create a text file in that created folder using the following code that doesn't seem to make it there. Instead, the code below creates the text file in the "files" folder that is in the same directory as the "cache" folder.
FileOutputStream fOut = null;
try {
fOut = openFileOutput("secret.txt",MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String str = "data";
try {
fOut.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
SO my question is, how do I properly designate the "MySecretFolder" to make the text file in?
I have tried the following:
"/data/data/com.example.myandroid.cuecards/cache/MySecretFolder", but it crashes my entire app if I try that. How should I properly save the text file in the cache/MySecretFolder?
use getCacheDir(). It returns the absolute path to the application-specific cache directory on the filesystem. Then you can create your directory
File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();
Please try this maybe helps you.
Ok, If you want to create the TextFile in Specific Folder then You can try to below code.
try {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MyFolder/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
File f = new File(rootPath + "mttext.txt");
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Just change
fOut = openFileOutput("secret.txt",MODE_PRIVATE);
to
fOut = openFileOutput(myDir+"/secret.txt",MODE_PRIVATE);
This will make secret.txt under MySecretFolder
getPrivateDir will create a folder in your private area (Context.MODE_WORLD_WRITEABLE- use what suits you from Context.MODE_...)
public File getPrivateDir(String name)
{
return context.getDir(name, Context.MODE_WORLD_WRITEABLE);
}
openPrivateFileInput will create a file if it doesn't exist in your private folder in files directory and return a FileInputStream :
/data/data/your.packagename/files
Your application private folder is in
/data/data/your.packagename
public FileInputStream openPrivateFileInput(String name) throws FileNotFoundException
{
return context.openFileInput(name);
}
If you package name is uno.due.com your app private folder is:
/data/data/uno.due.com
All directories underneath are weather created by you or by android for you. When you create a file as above it will go under:
/data/data/uno.due.com/files
Simple and easy code to create folder, file and write/append into the file
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/newfoldername/"; // it will return root directory of internal storage
File root = new File(path);
if (!root.exists()) {
root.mkdirs(); // create folder if not exist
}
File file = new File(rootPath + "log.txt");
if (!file.exists()) {
file.createNewFile(); // create file if not exist
}
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append("hi this will write in to file");
buf.newLine(); // pointer will be nextline
buf.close();
}
catch (Exception e) {
e.printStackTrace();
}
NOTE: It needs the Android External Storage Permission so add below line in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

How to append data to text files in the new line, ( \n does not work)

I am using this code as a part to write data to a text file, but I am not sure how I can append the data to the new line. "\n" does not seem to be working. Here, variable "data" has this format:
t=1, x=-3.1, y=19.0, z=-8.6
this part of the code iterates and the variable "data" is written each time; the current result is something like:
t=1, x=-6.9, y=-9.6, z=-6.9t=2, x=-1.4, y=6.2, z=7.0t=3, x=-1.4, y=6.1, z=6.9t=4, and so on, but what I would like is:
t=1, x=-6.9, y=-9.6, z=-6.9
t=2, x=-1.4, y=6.2, z=7.0
t=3, x=-1.4, y=6.1, z=6.9
Thanks in advance for your help.
String datatest = data.toString();
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/test");
directory.mkdirs();
String filename = "test.txt";
File file = new File(directory, filename);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(datatest + "\n");
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
try "\r\n"
and to make this answer longer :)

Categories

Resources