How do i save a .mp3 file to the Music directory on the sdCard.
The code below always saves the file to the downloads folder without any extensions
private FileOutputStream getOutStream(String fileName) throws FileNotFoundException{
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
String sdpath = Environment.getExternalStorageDirectory()
+ "/";
mSavePath = sdpath + "download";
File file = new File(mSavePath);
if (!file.exists()) {
file.mkdir();
}
File saveFile = new File(mSavePath, fileName);
return new FileOutputStream(saveFile);
}else{
mSavePath = mContext.getFilesDir().getPath();
return mContext.openFileOutput(fileName , Context.MODE_WORLD_READABLE);
}
}
mSavePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
File file = new File(mSavePath+"/filename.mp3");
Related
using camera2 api i m save file like this
if (Build.VERSION.SDK_INT <=Build.VERSION_CODES.P){
final String folderPath = Environment.getExternalStorageDirectory() + "/Pikpap/";
file1 = new File(folderPath);
} else{
file1 = new File( CameraFragment.view.getContext().getExternalFilesDir()+ "/Pikpap/");
}
if (!file1.exists()) {
file1.mkdirs();
}
String fullName = file1.getAbsolutePath() + "Pikpap" + currentTime+name + ".jpg";
File file = new File(fullName);
but some time file not save and image blank set on image view
this issue created on all devices
My UnZip class does not unzip whole the file. This class is called from another activity. My zip file is saved in the main directory of the phone's internal storage. The zip file has folders and some video.
What's wrong with this unzip?
What and how should I read file from zip' decompress and unzip is the same meaning?
Thanks for your help!
public class Unzip {
private static final String INPUT_ZIP_FILE = "sdcard/downloaded_issue.zip";
private static final String OUTPUT_FOLDER = "sdcard/Atlantis/";
public static void main()
{
Unzip unZip = new Unzip();
unZip.unZipIt(INPUT_ZIP_FILE, OUTPUT_FOLDER);
}
/**
* Unzip it
* #param zipFile input zip file
* #param outputFolder zip file output folder
*/
public void unZipIt(String zipFile, String outputFolder){
byte[] buffer = new byte[1024];
try{
//create output directory is not exists
File folder = new File(OUTPUT_FOLDER);
if(!folder.exists()){
folder.mkdir();
}
//get the zip file content
ZipInputStream zis =
new ZipInputStream(new FileInputStream(zipFile));
//get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while(ze!=null){
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : "+ newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
if (ze.isDirectory()) {
ze = zis.getNextEntry();
}
}
zis.closeEntry();
zis.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}
}
I think your 'while' loop is broken; you're only fetching the next entry if that next entry is a directory, while I assume you're probably trying to skip the directories.
Anyway, since you create the folders for all files you encounter, you can just skip the folder entries and write the file entries. The only exception would be the creation of empty folders.
Replacing the while-loop by this code should work:
while(ze!=null){
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : "+ newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
if (ze.isDirectory()) {
// create the folder
newFile.mkdirs();
}
else {
// create the parent folder and write to disk
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
// get the next item
ze = zis.getNextEntry();
}
I know with Kit Kat you can only write to your applications package specific directory on SD Cards. I was however under the impression you could still copy files from an SD card to local storage with the:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am simply testing if I can copy one file. If I am able to do that I will add the code to search the entire SD card DCIM folder. For now I have the following code (please forgive the messiness of the code, I have written C# and vb.net but java is still very new to me):
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "TCM";
File projDir = new File(dirPath);
if (!projDir.exists())
projDir.mkdirs();
String CamPath = projDir + File.separator + tv2.getText();
File projDir2 = new File(CamPath);
if (!projDir2.exists())
projDir2.mkdirs();
File LocalBuck = new File(projDir2 + File.separator );
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath();
File directory1 = new File (sdCard.getAbsolutePath() + "/DCIM");
File directory = new File(directory1 + "/100SDCIM");
File Buckfile = new File(directory, "/BigBuck.jpg");
try {
exportFile(Buckfile, LocalBuck);
} catch (IOException e) {
e.printStackTrace();
}
Here is my code for the export function/application:
private File exportFile(File src, File dst) throws IOException {
//if folder does not exist
if (!dst.exists()) {
if (!dst.mkdir()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HHmmss").format(new Date());
File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//Straight to Error Handler
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(expFile).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
return expFile;
}
Here is what my emulator looks like:
Looking for: Debug of SD Location
Should Find It?: EmulatorShowingSd
Question: Am I even able to copy a file from the SD card to local storage after KitKat; if so what is wrong in the code causing the exception to be thrown when it tries to access the SD card file?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Moving my db to sd card not working
I'm trying to save a sqlite file to my sdcard. I'm using the code from this question
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "\\data\\com.test.mytest\\databases\\test_db";
String backupDBPath = "test_db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
}
This is a very highly rated answer, so I would think it should work pretty simply. I get no errors in logcat. I don't see any created directory/created files. I also have the "write to external" permission in my manifest.
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "/data/packagename/databases/DATABASENAME";
String backupDBPath = "/backup/"+"main.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} else {
Log.e(TAG, "File does not exist: " + currentDBPath);
}
Don t forget to declare permission in amnifest file
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I am trying to have the program upload all files in a designated filepath on a local directory onto Google Drive. Having accomplished the opposite with download all the files in a folder, I thought that I would stick with the same methodology of listing all the files in local directory first, then uploading them one by one as each file is listed.
This code along lists all the names of the files in a designated filepath
private static File uploadFile(Drive service, String originfolder) {
java.io.File dir = new java.io.File(originfolder);
String [] fileslist = dir.list();
for (String file : fileslist) {
System.out.println(file);
I know that the code to upload a single file is as below
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
as seen from here
Trying to combine the two results in the following snippet:
private static File uploadFile(Drive service, String originfolder) {
java.io.File dir = new java.io.File(originfolder);
String [] fileslist = dir.list();
for (String file : fileslist) {
System.out.println(file);
File uploadfile = new File();
uploadfile.setName(originfolder);
FileContent mediaContent = new FileContent("image/jpeg", originfolder);
File uploadedfile = service.files().create(uploadfile, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file);
}
}
The error I get from cmd is this
error: incompatible types: String cannot be converted to File
FileContent mediaContent = new FileContent("image/jpeg", originfolder);
The planned intent is to upload the entire content of the following file hierarchy onto Google Drive, whilst keeping the same file names and mimetype.
Logs (folder).
--- bin (folder)
------ approx 1 GB of .bin files
--- 2 xml files
Solved it
For anyone who wants to know, code ended up looking like this
private static void uploadFile(Drive service, String originfolder) {
try {
java.io.File dir = new java.io.File(originfolder);
String [] fileslist = dir.list();
for (String file : fileslist) {
System.out.println(file);
File uploadfile = new File();
uploadfile.setName(file);
java.io.File filePath = new java.io.File(originfolder + file);
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File uploadedfile = service.files().create(uploadfile, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file);
}
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}
}