EROS | Read Only file system error - java

In my android app, i am logging errors in a txt file. But when i try to create file , i face an error Java.io.IOException: open failed: EROS( Read Only file system error). I have added write permissions in AndroidManifest.xml but no difference. How to fix it ?
code
try {
File file =new File("Log.txt");
if(!file.exists()){
file.createNewFile();
}
catch (Exception e)
{
Log.w("tun tun", e.toString());
}

Do this way
To store on external storage(SDCARD)
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Log.txt");
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
Log.w("tun tun", e.toString());
}
To store In internal storage
try {
File file = new File(context.getCacheDir() + File.separator + "Log.txt");
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
Log.w("tun tun", e.toString());
}

try some below codes:-
Problem is you are not adding path.
String filePath = context.getFilesDir().getPath().toString() + "/fileName.txt";
File f = new File(filePath);
or
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
refrence
or
path = Environment.getExternalStorageDirectory();
File file = new File(path, "/" + fname);
Data directory has no read/write permission in Android

Related

Can't create folder in internal storage

Well, I'm trying to create a folder in my internal storage.
I have watched some tutorial but it's not working at all.
private void createDir() {
String folderName;
folderName = "myFolder";
File file = new File(Environment.getExternalStorageDirectory(), folderName);
if(!file.exists()){
file.mkdir();
Toast.makeText(getContext(),"Successful", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(),"Folder already exist", Toast.LENGTH_SHORT).show();
}
}
This is my method to create the new directory.
When I launch it, I receive the Toast "Successful" all the time.
But the directory is never created.
Just below the code for the permissions.
if(!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.SEND_SMS)){
String[] permissions = {Manifest.permission.WRITE_CALL_LOG,Manifest.permission.SEND_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_SMS};
ActivityCompat.requestPermissions(getActivity(),permissions,1);
}else{
lay_dataset1=view.findViewById(R.id.lay_dataset1);
messagePerm();
}
Here my manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Can someone explain what is happening :)
EDIT :
private void copyAssets() {
AssetManager assetManager = getContext().getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getContext().getExternalFilesDir(null).getParent().replace("files","myfolder"), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I tried this, I was able to move files that were in my "asset" folder at the same level as the "files" directory so why shouldn't I have the right to create a folder in this same location ?
At the first time you run your application, the app external storage directory
at Android/data/<package.name>/files is not created until you call this method getExternalFilesDir(null) Twice.
So try this code..
//Essential for creating the external storage directory for the first launch
getExternalFilesDir(null);
/*
output->> /storage/emulated/0/Android/data/<package.name>/files
*/
Log.i("HINT",getExternalFilesDir("").getAbsolutePath());
//Or create your custom folder
File outFile = new File(getExternalFilesDir(null).getParent(),"myfolder");
//make it as it is not exists
outFile.mkdirs();
/*
output->> /storage/emulated/0/Android/data/<package.name>/myfolder
*/
Log.i("HINT",outFile.getAbsolutePath());

Improper Resource Shutdown or Release

Description:
In the code below What am i doing wrong in the code below, in my code audit i got improper resource shutdown or release.
I tried taking out the close and flush from the code below
File someFile = new File(fileName);
fos = new FileOutputStream(someFile);
fos.write(data);
fos.flush();
fos.close();
Main code:
FileOutputStream fos=null;
try {
Hashtable hash = responseBlob.getAllAttachments();
Enumeration e = hash.elements();
while (e.hasMoreElements()) {
SBADataAttach tmpAttach = (SBADataAttach) e.nextElement();
String tag = tmpAttach.getTag();
byte[] data = tmpAttach.getData();
// encode compressed file
if (hasTag(tag))
mimeResponse.addPart(tag, Base64.encodeBytes(data)
.getBytes());
else
mimeResponse.addPart(tag, data);
try {
if (this.configData.getBlobPath() != null)
{
// save compressed file
String fileName = File.separatorChar + "tmp"
+ File.separatorChar + tag;
Log.theLogger.debug("XisServlet.process() ... "
+ "Save compressed file = " + fileName);
File someFile = new File(fileName);
fos = new FileOutputStream(
someFile);
fos.write(data);
fos.flush();
fos.close();
}
} catch (Exception zipe) {
Log.theLogger.error(zipe.getMessage(), zipe);
}
}
} catch (SBADataException sde) {
// cannot detach files from blob
Log.theLogger.error(sde.getMessage(), sde);
}
finally {
try {
if( fos!=null ) {
fos.close();
}
} catch(IOException e) {
Log.theLogger.error(e.getMessage(), e);
}
}
I don't get any error. But in the Appsec finding i getImproper Resource Shutdown or Release
try{
//open resources
File someFile = new File(fileName);
fos = new FileOutputStream(someFile);
fos.write(data);
}
catch(Exception e1){
//handle exception
}finally{
//close resources
fos.flush();
fos.close();
}
}

create a temporary file with a specified name in java

I have a Byte[] array that i want to put it's content into a temporary file .
I have tryied to do it like this
try {
tempFile = File.createTempFile("tmp", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(sCourrier.getBody());
} catch (IOException e) {
e.printStackTrace();
}
but i want that I specify the filename by myself so not generated by the jvm
You can directly give the location and file name or You can access local filesystem and find the temp directory
String tempDir=System.getProperty("java.io.tmpdir");
you can use temp directory and your custom file name.
public static void main(String[] args) {
try {
String tempDir=System.getProperty("java.io.tmpdir");
String sCourrier ="sahu";
File file = new File(tempDir+"newfile.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(sCourrier.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
You can use Guava Files.createTempDir():
File file = new File(Files.createTempDir(), fileName.txt);
But because the API is deprecated and they also recommend to use Nio with more params:
Path createTempDirectory(String prefix, FileAttribute<?>... attrs)
so it would be better if you have a method yourself:
File createTempFile(String fileName, String content) throws IOException {
String dir = System.getProperty("java.io.tmpdir");
File file = new File(dir + fileName);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(content.getBytes(StandardCharsets.UTF_8));
}
return file;
}

How to create File object from assets folder?

I am trying to read a pdf file from my assets folder but I do not know how to get the path of pdf file.
I right click on pdf file and select "copy Path" and paste it
Here is the another screen shot of my code:
Here is my code:
File file = new File("/Users/zulqarnainmustafa/Desktop/ReadPdfFile/app/src/main/assets/Introduction.pdf");
if (file.exists()){
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
this.startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application available to view PDF", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this, "File path not found", Toast.LENGTH_LONG).show();
}
I always get file not found, Help me to create File object or let me know how I can get the exact path for a file I also tried with file:///android_asset/Introduction.pdf but no success. I also tried with Image.png but never gets file.exists() success. I am using Mac version of Android studio. Thanks
get input stream from asset and convert it to a file object.
File f = new File(getCacheDir()+"/Introduction.pdf");
if (!f.exists())
try {
InputStream is = getAssets().open("Introduction.pdf");
byte[] buffer = new byte[1024];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
Short converter (storing asset as cache file) in Kotlin:
fun fileFromAsset(name: String) : File =
File("$cacheDir/$name").apply { writeBytes(assets.open(name).readBytes()) }
cacheDir is just shorthand for this.getCacheDir() and should be predefined for you.
Can you try this code
AssetManager am = getAssets();
InputStream inputStream = am.open("Indroduction.pdf");
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File("new FilePath");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
Then try with
File file = new File("new file path");
if (file.exists())

why my method retruniing null value?

I have declared variable directory as a global and using that variable below in my returnData method nut it is returning null value.
public void SaveImage(String FileName, Bitmap mBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File directory = new File(root + File.separator + "HMS_BARCODE");
directory.mkdirs();
//create a file to write bitmap data
File f = new File(directory, FileName + ".png");
Log.e("dir", "" + directory);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", "IOException");
}
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bytearray = bos.toByteArray();
//Write bytes in file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bytearray);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", "" + e);
}
} else {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
directory = new File(root + File.separator + "HMS_BARCODE");
if (!directory.exists()) {
directory.mkdirs();
}
File f = new File(directory, FileName + ".png");
Log.e("dir1", "" + directory);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", "IOException");
}
Log.e("dir1", "" + directory);
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bytearray = bos.toByteArray();
//Write bytes in file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bytearray);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", "" + e);
}
}
}
// this is method returning null value I want want that directory
// value to pass to another class
public File returnData() {
Log.e("Exception", "" + directory);
return directory;
}
Please format your question correctly, it is hard to read. From what I can see your directory variable is not global, it is local for saveImage method.
If you want to have access to the directory variable from different methods of the same class instance, then you need to declare it as a class variable. For example:
public class MyClass {
private File directory;
public void saveImage(...) {....}
public File returnData(...) {...}
}
You must call SaveImage method in your returnData method :
//this is method returning null value i want want that directory value to pass to another class
public File returnData(){
SaveImage(.../*the parameters*/);
Log.e("Exception", "" + directory);
return directory;
}

Categories