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
Related
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>
When trying to create a simple .txt or .xml external file (NOT on SD card), my app is throwing a FileNotFoundException. If I let the system pick the path (returns /storage/emulated/legacy) it throws EACCES (permission denied). Same as when I set the path manually to "/android/data" (returns /storage/emulated/0/android/data) or "/download" (returns /storage/emulated/0/Download) - both throw EACCES. If I set path to "/document" it throws ENOENT (no such file or directory).
As see below in my code, I do a check before to make sure that external storage is available and not read-only.
I ran this on 2 devices, running 4.4.2 and 4.4.4
I also added
"android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
in the manifest as suggested in SO answers to try and force the device to use it's own file system and not the PC's when running app through USB, but it seems to keep giving me a path derived from /emulated/
I try debugging from the device itself using the developer options and thus eliminating the possibility of the app accessing the PC's storage, but the debugger on the device just hangs trying to attach.
Of course I have as well:
"android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
This is very frustrating as there are some similar questions on SO but with very accepted answers.
public static File getExternalStorageDirectory() {
Log.i("EXTERNAL STORAGE DIR", EXTERNAL_STORAGE_DIRECTORY.toString());
return EXTERNAL_STORAGE_DIRECTORY;
}
public static final File EXTERNAL_STORAGE_DIRECTORY = getDirectory("EXTERNAL_STORAGE", "android/data");
public static File getDirectory(String variableName, String defaultPath) {
String path = System.getenv(variableName);
return path == null ? new File(defaultPath) : new File(path);
}
public boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
public void writeToSettingsFile(String name, String value){
// File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "/settings.txt");
// File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), fileUrl);
// File myDir = getDirectory("EXTERNAL_STORAGE", "android/data");
// File myDir = getExternalStorageDirectory();
// File myDir = new File("download");
File myDir = new File(Environment.getExternalStorageDirectory() + "/android/data");
if(!myDir.exists()){
myDir.mkdirs();
}
try{
String fname = "settings.txt";
File file = new File (myDir, fname);
FileOutputStream fOut = new FileOutputStream(file);
Toast.makeText(context, "you made it, fOut!!!!", Toast.LENGTH_LONG).show();
props.setProperty(name, value);
props.store(fOut, "Settings Properties");
// props.storeToXML(fOut, "Settings Properties");
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("WTF", "No file found!");
}
catch (IOException e) {e.printStackTrace();
}
}
I think the problem is in your this line
android:maxSdkVersion="18" .
Cause You are testing on 4.4.2. And this device has api level 19.
Okay this is the solution :
public void writeToSettingsFile(String name, String value){
// File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "/settings.txt");
// File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), fileUrl);
// File myDir = getDirectory("EXTERNAL_STORAGE", "android/data");
// File myDir = getExternalStorageDirectory();
// File myDir = new File("download");
File myDir = new File(this.getExternalFilesDir(null), name);
if(!myDir.exists()){
myDir.mkdirs();
}
try{
String fname = "settings.txt";
File file = new File (myDir, fname);
FileOutputStream fOut = new FileOutputStream(file);
fOut.write(value.getBytes());
// props.storeToXML(fOut, "Settings Properties");
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("WTF", "No file found!");
}
catch (IOException e) {e.printStackTrace();
}
}
Try this method. The problem was you cant get internal directory like this
File myDir = new File(Environment.getExternalStorageDirectory() + "/android/data"); // You don't have the permission to do this
if you want to write on internal storage you can get directory like this
File myDir = new File(this.getExternalFilesDir(null), name);
And you can take a look to For more information about saving files
I am trying to write files in the external SD card folder. Even after having set the required permission in the manifest file, I am unable to write on the external SD card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code:
String path = "/mnt/extsd/nit.txt";
File myFile = new File(path);
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
}
try {
FileOutputStream fostream = new FileOutputStream(myFile);
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
bwriter.write("Hi welcome ");
bwriter.newLine();
bwriter.close();
oswriter.close();
fostream.close();
txtText.setText("success");
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
On the other hand when I use ES File Explorer and try to create a file, it creates it without any issues.
Don't use the absolute path String path = "/mnt/extsd/nit.txt"; because you never know about android device being used by users. Rather you can get the external storage directory path by using Environment.getExternalStorageDirectory().toString().
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
File log = new File(Environment.getExternalStorageDirectory(), "your_file_name.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write("any data");
} catch (Exception e) {
}
And don't forget to close the streams.
First check sd-card is available or not.
String state = Environment.getExternalStorageState();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File folder = folder = new File(extStorageDirectory, "FolderName");
if(!folder.exists())
{
folder.mkdir();//making folder
}
File file = new File(folder,"Filename");//making file
}
Please try this code, it work in my application.
I'm a newbie Android developer. I have loaded an image using universal-image-loader and I would like to save it on my sd card. The file is created in the desired directory with the correct filename, but it always has a size of 0. What am I doing wrong?
A relevant snippet follows:
PS: The image already exists on disk, it's not being downloaded from the Internet.
private void saveImage(String imageUrls2, String de) {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = de;
File myDir = new File(SDCardRoot+"/testdir");
Bitmap mSaveBit = imageLoader.getMemoryCache();
File imageFile = null;
try {
//create our directory if it does'nt exist
if (!myDir.exists())
myDir.mkdirs();
File file = new File(myDir, filename);
if (file.exists())
file.delete();
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bos.flush();
bos.close();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
Toast.makeText(getApplicationContext(),
R.string.diskful_error_message, Toast.LENGTH_LONG)
.show();
}
Log.i("filepath:", " " + filepath);
}
Yes, your code creates an file on sdcard_root/testdir/de only, and didn't write anything to it. Is "imageUrls2" the source image file? If yes, you can open that file with BufferedInputStream, read the data from BufferedInputStream, and copy them to output file with bos.write() before bos.flush() and bos.close().
Hope it helps.
I think I have looked at all of the relevant questions and I still can't get this to work.
Here is the code:
File sdCard = Environment.getExternalStorageDirectory();
File directory= new File (sdCard.getAbsolutePath() + appName);
directory.mkdirs();
File file = new File(directory,fileName);
The folder is created, but I get an error saying the file does not exist. appName is a string containing the name of the folder and that works correctly. fileName is a string containing the name of the file I want to include.
I have included the permission in the manifest.
What am I doing wrong?
Update:
The code tries to make a subdirectory and a file at the same time, which hidden because the code uses a named String rather than a String literal. Adding an intermediate step to create the subdirectory solved the problem.
If the directory is created, then you're on the right track. In your code you are not actually creating the file on the SD card. If you need to create the file, then do this:
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + appName + "/" + fileName);
directory.mkdirs();
file.createNewFile()
This is notional only. It would be much better to actually separate your fileName into a separate subfolder and the actual file and handle them separately.
Try this out:
In this I am creating a text file (.txt file) of a string.
public void createFileFromString(String text)
{
File logFile = new File("sdcard/xmlresponseiphone.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Test this, and see what are you missing :)
Try with something like this. In this case I'm saving an image!
For creating the directory:
File directory = new File(Environment.getExternalStorageDirectory()
+ File.separator + appName);
directory.mkdirs();
And for saving into it
public void save(Bitmap graph, Context context, String name, String time, boolean now) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
graph.compress(Bitmap.CompressFormat.PNG, 100, bytes);
// you can create a new file name "test.jpg" in sdcard folder.
String fileName = "";
if (now){
fileName = getDateTime()+"_00"+".png";
}
else {
fileName = time.replace(".txt", ".png");
}
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "appName/" + fileName);
f.createNewFile(); // write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
}
I think the trick is in File.separator!