i m a beginner in android ...i want to know why in my code the fos becoming null here is my main activity.java file
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileOutputStream fos = null;
TextView tv = (TextView) findViewById(R.id.tv);
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File dir = new File(root.getAbsolutePath() + "/musics");
dir.mkdir();
File file = new File(dir, "myData.txt");
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("good morning".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("fos", "null");
}
}
} else {
Toast.makeText(MainActivity.this, "permission not granted", Toast.LENGTH_LONG).show();
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
}
tv.setText(fos + "");
}
#Override
public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) {
FileOutputStream fos = null;
if (requestCode == 101 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File dir = new File(root.getAbsolutePath() + "/musics");
dir.mkdir();
File file = new File(dir, "myData.txt");
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("good morning".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("fos", "null");
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
and here is the log msg
05-25 16:37:06.311 21858-21858/com.example.kalyan.musicextra E/fos: null
This line throws an exception so your fos variable will be null:
fos = new FileOutputStream(file);
You can find the exception in the logcat or add a breakpoint to the catch part and debug it, you will see the exception.
Related
I am using this code to save some text in the external storage.
String fileName = "zadTest";
String text = "Hello World!";
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File textFile = new File(Environment.getExternalStorageDirectory(),fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(textFile);
fos.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But I don't know where to look for it exactly so I can't check if I am doing this correctly and I don't know if I really put some data into external storage. I checked my SD card but couldn't find it I also tried to run this app on emulator but also cant find the file.
I have put these in the manifest:
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
Additional question: Should I bother with "finally" in try/catch blocks or should I just put all the code in "try" and skip "finally"?
Here I placed code with run-time permission put this and check again
Put this permission in on create and call request permission in that.
private static final int REQUEST_CODE = 101;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermission(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
} else {
String fileName = "zadTest";
String text = "Hello World!";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File textFile = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(textFile);
fos.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
After permission code, call this method
protected void requestPermission(String[] permissionType, int
requestCode) {
ActivityCompat.requestPermissions(this,
permissionType, requestCode
);
}
I've created Test.txt on sdcard and write string "test example" on it.
after that, I replace string "test" by "etc" in Test.txt.
this is my code :
String origin_str, old_str , new_str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t2);
origin_str = "test example";
old_str = "test";
new_str = "etc";
Button bt_create2 = (Button)findViewById(R.id.bt_createfileT2);
bt_create2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
File file = new File(newFolder, "Test" + ".txt");
if (!file.exists()) {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(origin_str);
myOutWriter.close();
fOut.close();
}
} catch (Exception e) {
System.out.println("e: " + e);
}
}
});
Button bt_replacefileT2 = (Button)findViewById(R.id.bt_replacefileT2);
bt_replacefileT2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] data1 = new byte[1024];
while ( -1 != (len = in.read(data1)) ){
if(new String(data1, 0, len).contains(old_str)){
String s = "";
s = s.replace(old_str, new_str);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
with this code, it was create Test.txt on sdcard and write "test example" on it.
but when replace string "test" by "etc", it not working.
how to fix it?
I will give my code, always worked for me :)
Hope thi can help you :DD
public void saveString(String text){
if(this.isExternalStorageAvailable()){
if(!this.isExternalStorageReadOnly()){
try {
FileOutputStream fos = new FileOutputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeBytes(text);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
//Toast.makeText(main, "Eror saving String", Toast.LENGTH_SHORT).show();
}
}
}
}
private static boolean isExternalStorageAvailable(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(estadoSD))
return true;
return false;
}
private static boolean isExternalStorageReadOnly(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
return true;
return false;
}
public String getString(){
FileInputStream fis = null;
ObjectInputStream ois = null;
if(this.isExternalStorageAvailable()) {
try {
fis = new FileInputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ois = new ObjectInputStream(fis);
String text = (String)ois.readObject();
return familia;
} catch (FileNotFoundException e) {
//Toast.makeText(main, "The file text doesnt exist", Toast.LENGTH_SHORT).show();
} catch (StreamCorruptedException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch(EOFException e){
try {
if(ois != null)
ois.close();
if(fis != null)
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
//Toast.makeText(main, "eror reading file", Toast.LENGTH_SHORT).show();
} catch (ClassNotFoundException e) {
//Toast.makeText(main, "String class doesnt exist", Toast.LENGTH_SHORT).show();
}
}
return null;
}
try this
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = line.replace(old,new);
}
br.close();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.write(line);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
I want to write string of data in a file in android . That is why I have the following code :
public String DumpFile(String fileName,String data)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_data");
myDir.mkdirs();
if(myDir.exists())
Toast.makeText(this, "Directory exists" ,Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "directory not exists " ,Toast.LENGTH_LONG).show();
// Random generator = new Random();
String fname = fileName;
// showToastOnUiThread("File Name: "+fname+" and Data: "+data,
// Toast.LENGTH_LONG);
File file = new File(myDir, fname);
Toast.makeText(this, "Link is "+file.getAbsolutePath(),Toast.LENGTH_LONG).show();
// Toast.makeText(this, "Content is "+data,Toast.LENGTH_LONG).show();
OutputStream bos = null;
FileOutputStream out = null;
if (file.exists())
file.delete();
try {
out = new FileOutputStream(file);
bos = new BufferedOutputStream(out);
bos.write(data.getBytes());
bos.flush();
// out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return fname;
}
But when I have run the code , I have got the Toast that directory not exists . Where is the error ? Can you help me ?
Add the permission to your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
File albumF = getVideoAlbumDir();
String path = albumF.getAbsolutePath();
// path =/storage/emulated/0/Pictures/.MyImages (Hidden folder)
// fileSelected.fileName()=IMG_20140417_113847.jpg
File localFile = new File(path + "/" + fileSelected.fileName());
Log.v("", "file exist===" + localFile.exists());
if (!localFile.exists()) {
Log.v("", "inside if===");
Log.v("", "Parent Filet===" + localFile.getParentFile());
localFile.getParentFile().mkdirs();
// localFile.createNewFile();
copy(fileSelected, localFile);
} else {
Log.v("", "inside else===");
mCurrentPhotoPath = localFile.getAbsolutePath();
uploadMediaFile();
}
This copy method copies data from dropbox file to my local storage.
private void copy(final Entry fileSelected, final File localFile) {
final ProgressDialog pd = ProgressDialog.show(ChatActivity.this,
"Downloading...", "Please wait...");
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
DropboxInputStream fd;
try {
fd = mDBApi.getFileStream(fileSelected.path,
localFile.getAbsolutePath());
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(
localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
pd.dismiss();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
android.os.Message msg = new android.os.Message();
msg.arg1 = 100;
if (msg.arg1 >= 100) {
progressHandler.sendMessage(msg);
mCurrentPhotoPath = localFile.getAbsolutePath();
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
I am creating file in a folder using localFile.getParentFile().mkdirs();
I got above error when I upload this file to server.
how to fix this?
If you've tried all other options - and problem still persists - then maybe you have a case when the file you want to create matches name of already existing directory.(which might be earlier created my some call to mkdirs() maybe accidentally).
Example:
You want to save file Test\test.pdf but you already have folder Test\Test.pdf\