I'm trying to write a text file and save it in the android external storage, but file is not showing and I don't get any errors.
Here is my code:
String r;
String fname= "readme.txt";
r = Environment.getExternalStorageDirectory().toString();
File myDir = new File(r);
if (!myDir.exists()) {
myDir.mkdirs();
}
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
Out.write(wfile)
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Try something below. You can add validations to check whether file exists or not, as you please.
File file = new
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "readme.txt");
FileOutputStream out = new FileOutputStream(file);
out.write(wfile);
out.flush();
out.close();
MediaScannerConnection.scanFile(mContext, new String[] { file.toString() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Just FYI, Environment.DIRECTORY_DOCUMENTS may does not exists in older android versions. Then you may have to add a validation to check that and create a directory if not.
Related
I cant save the bitmap in my internal storage, when looking at the logcat, it says that "java.io.IOException: No such file or directory"
here is my code
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY );
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
Log.d("hhhhh",wallpaperDirectory.toString());
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(MainActivity.this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
I didnt know what I'm doing wrong, help is much appreciated
I'm trying to make an app that uploads a file to dropbox and downloads it.
Uploading seems to work, downloading doesn't. Also it doesn't actually upload from my SD card but from my phone internal memory.
saveOnDropbox() uploads a file.txt from phone/MyFiles/file.txt to dropbox app folder.
saveOnDevice() - something happens when I use this, but the file doesn't get neither to my phone or SD card
public void saveOnDropBox() throws IOException, DropboxException {
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + "/MyFiles/file.txt");
FileInputStream inputStream = new FileInputStream(file);
DropboxAPI.Entry response = dropboxAPI.putFile("/file.txt", inputStream,
file.length(), null, null);
Log.i("D bExam pleLog", "The uploaded file's rev is: " + response.rev);
}
public void saveOnDevice() {
FileOutputStream outputStream = null;
try {
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + "/MyFiles/file.txt");
outputStream = new FileOutputStream(file);
DropboxAPI.DropboxFileInfo info = dropboxAPI.getFile("/file.txt", null, outputStream, null);
} catch (Exception e) {
System.out.println("Som ething w ent w rong: " + e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
System.out.println("___" + e);
}
}
}
}}
Appreciate any help.
I'm trying to get a image from android Photos app using the share option that point to my PhotoGetFromGallery activity. Here is the code:
public void copy(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
String sourcePath = getRealPathFromURI(imageUri);
if(isExternalStorageWritable()) {
if (imageUri != null) {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
String destinationImagePath = sd + "/Pictures/MyAppImgFolder/";
File source = new File(data, sourcePath);
String fileName = source.getName();
File destination = new File(sd, destinationImagePath + fileName);
try {
copy(source, destination);
} catch (Exception e) {
Log.e("COPY IMAGE ERROR", e.toString() + ". Destination Path is " + destinationImagePath.toString() + " and Source path is "+ sourcePath);
}
}
}
}
sourcePath string returns the correct image path (ex. /storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg). However, I'm getting the FileNotFoundException because Environment.getDataDirectory() returns /data/storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg.
Here is my log:
E/COPY IMAGE ERRORīš java.io.FileNotFoundException: /data/storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg: open failed: ENOENT (No such file or directory). Destination Path is /storage/emulated/0/Pictures/MyAppImgFolder/ and Source path is /storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg
Here is my AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
My question is how can I get, if possible, any path of images stored at Photos app or Android Gallery?
You should not be using getDataDirectory - you are already being handed a complete path, starting with "/storage" Use the single argument File() constructor passing only the sourcePath, like this:
File sd = Environment.getExternalStorageDirectory();
String destinationImagePath = sd + "/Pictures/MyAppImgFolder/";
//sourcePath is already a full path name
File source = new File(sourcePath);
//redundant String fileName = source.getName();
File destination = new File(destinationImagePath + sourcePath);
//You are proposing many new subdirectories, so you must create them
destination.getParentFile()makeDirs();
//now you can continue with your copy attempt
I managed to solve the problem. Follows the code that works . Thanks to Chris Stratton for guiding me in this matter.
File sd = Environment.getExternalStorageDirectory();
String destinationImagePath = sd + AppConstant.PHOTO_ALBUM;
File imagePath = new File(destinationImagePath);
File source = new File(sourcePath);
String fileName = source.getName();
File destination = new File(destinationImagePath + fileName);
if (!imagePath.exists()) {
imagePath.mkdirs();
try {
copy(source, destination);
Toast.makeText(getApplicationContext(), "Success! File was copy from " + sourcePath + " to " + destinationImagePath, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("COPY IMAGE ERROR", e.toString());
}
} else if(destination.exists() && !destination.isDirectory()){
Toast.makeText(getApplicationContext(), "Image is already on your image folder", Toast.LENGTH_LONG).show();
}
So I'm trying to basically write some logs to a text file so i can view it later. I'm running this on a physical phone, not the emulator. I've tried so many different variations, and the most i got was it writing to data/data and storage/emulated but i can never access my file. Any help would be appreciated. Some of my latest undeleted examples have been:
String filename = "myfile.txt";
try {
File path = new File(context.getFilesDir(), "myfolder");
if (!path.exists())
path.mkdir();
File output = new File(path, filename);
BufferedWriter buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
Log.d("Success",
"Successfully wrote a file " + context.getFilesDir());
} catch (Exception e) {
e.printStackTrace();
}
and
final String appPath = String.format("%s/Datafiles",
context.getFilesDir());
File path = new File(appPath);
if (!path.exists()) {
path.mkdir();
}
String fileName = String.format("%s/filedemo.txt", appPath);
and
try {
String filename = "myfile.txt";
File path = new File(Environment.getRootDirectory(), "myfolder");
if (!path.exists())
path.mkdir();
File output = new File(path, filename);
BufferedWriter buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
Log.d("Success",
"Successfully wrote a file " + context.getFilesDir());
} catch (Exception e) {
e.printStackTrace();
}
Both of the following put it under /storage/emulated/0/Android/data/com.example.simplelte/files/system/stuff/test.txt
and
/storage/emulated/0/Android/data/com.example.simplelte/files/storage/emulated/0/stuff/test.txt
respectively
try {
File file = new File(context.getExternalFilesDir(Environment
.getRootDirectory().getCanonicalPath()), "stuff");
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
File output = new File(file, "test.txt");
BufferedWriter buff;
buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
buff.close();
Log.d("Success", output.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and
try {
File file = new File(context.getExternalFilesDir(Environment
.getExternalStorageDirectory().getCanonicalPath()),
"stuff");
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
File output = new File(file, "test.txt");
BufferedWriter buff;
buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
buff.close();
Log.d("Success", output.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and much more. I've followed every example I can think of. I literally just want to view the text file under Computer\Nexus 5\Internal storage\ I'm just a simple man with simple desires. Why does this have to be so complicated.
Have you tried this ?
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/");
File file = new File(dir, "text.txt");
FileOutputStream f = new FileOutputStream(file);
Here i have Bookfolder in that few more folders(english,hindi,japanese).Converting english,hindi,japanese to english.zip,hindi.zip and japanese.zip.Everything is working fine and i'm keeping zip files and folders inside Bookfolder,this thing i'm doing using with java.But when i'm unzipping manually the zip file ex:english.zip ,right click on that extract here then showing error as UNEXPECTED END OF ARCHIVE.This is my code.
public void foldertToZip(File zipDeleteFile) {
//System.out.println(zipDeleteFile);
File directoryToZip = zipDeleteFile;
List<File> fileList = new ArrayList<>();
//System.out.println("---Getting references to all files in: " + directoryToZip.getCanonicalPath());
getAllFiles(directoryToZip, fileList);
//System.out.println("---Creating zip file");
writeZipFile(directoryToZip, fileList);
//System.out.println("---Done");
}
public static void getAllFiles(File dir, List<File> fileList) {
try {
File[] files = dir.listFiles();
for (File file : files) {
fileList.add(file);
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
getAllFiles(file, fileList);
} else {
System.out.println("file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
}
}
public static void writeZipFile(File directoryToZip, List<File> fileList) {
try {
//try (FileOutputStream fos = new FileOutputStream(directoryToZip.getName() + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos)) {
File path = directoryToZip.getParentFile();
File zipFile = new File(path, directoryToZip.getName() + ".zip");
try (FileOutputStream fos = new FileOutputStream(zipFile)) {
ZipOutputStream zos = new ZipOutputStream(fos);
for (File file : fileList) {
if (!file.isDirectory()) { // we only zip files, not directories
addToZip(directoryToZip, file,zos);
}
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {
try (FileInputStream fis = new FileInputStream(file)) {
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
}
}`
while i'm extracting new zip file(eg:english.zip) it showing error as unexpected end of archieve (i think not zipping exactly)'
You need to close ZipOutputStream in writeZipFile() method;
for (File file : fileList) {
if (!file.isDirectory()) { // we only zip files, not directories
addToZip(directoryToZip, file,zos);
}
}
//here close zos
zos.close();
I was missing media type on ResponseEntity object and therefore I got this error information during extracting zip archive.
That means when calling rest api to download zip archive with files then needed information needs to be passed within ResponseEntity (media type application/zip, header info, cache info, etc.).
Another observation
is that I was missing correct return response type from angular side. There must be responseType as blob and not as text. That caused me the main issue.
Angular side:
getZIPData(id: number) {
const path = resolveBase() + 'rest-api-path' + id
return this._http.get(path, { observe: 'response', responseType: 'blob' });
}
It might help somebody.