Here's a code of MainActivity.java to save a file named filename.txt in App's Internal Storage, which is working fine.
package com.bla.smthing;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am able to see the file by File Explorer of Android Studio. How can I save the file in a directory say files/Somefolder/otherfolderchild/filename.txt?
Currently, it is saving as files/filename.txt
Do I need to create additional parent file directories for that?
Try this it might help you. For the above marshmallow version please check the write permissions.
public void saveToExternalStorage() {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/directoryName";
try
{
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, "fileName.txt");
if(file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
fOut.flush();
fOut.close();
}
catch (Exception e)
{
Log.e("saveToExternalStorage()", e.getMessage());
}
}
Related
I am trying to open a CSV file downloaded into internal storage for reading purpose alone. This is the code I have used:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.io.FileInputStream;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
try {
String FileName = "/storage/emulated/0/Download/MyDocument.csv";
FileInputStream fis = openFileInput(FileName);
fis.read();
fis.close();
Toast.makeText(getBaseContext(),"File Access Permitted",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(),"File Access Denied",Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
While the file is downloaded and I am able to open it in File Manager, the above code does not work. How do I achieve the required functionality?
As per this stackoverflow question's accepted answer, you could try this:
public String readFileFromDownloads(String fileName) {
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!downloadsDir.exists()) return null;
File file = new File(downloadsDir, fileName);
if (!file.exists()) return null;
try {
StringBuilder fileContent = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
fileContent.append(line);
fileContent.append('\n');
}
br.close();
return fileContent.toString();
} catch (IOException ex) {
//Handle error
return null;
}
}
And then call readFileFromDownloads("MyDocument.csv"); from inside your onClick(); method.
Also, you might need to add android.permission.READ_EXTERNAL_STORAGE to your Manifest and handle Android 6.0 new permission system as per Android Docs.
I have written simple code to save data into text files internally. But, after running the code, I don't know where I can find the required file. Additionally, I find an error message in the log cast as
"SPAN_EXCLUSIVE_EXCLUSIVE"
package com.example.saving_files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
File file;
FileOutputStream fos;
String FlieName = "output.text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file = new File(FlieName);
try {
fos = openFileOutput(FlieName, MODE_PRIVATE);
fos.write(122);
} catch (FileNotFoundException e) {
Log.d("output", file.getAbsolutePath());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
file = getFilesDir();
Log.d("output_path", file.getAbsolutePath());
}
}
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, "filename");
FileOutputStream f = new FileOutputStream(file);
This code will create new file in the root directory of your SD. Dont forget to add
<uses-permission> to write to SD in your manifest
Check this code and comments;
File sdcard = Environment.getExternalStorageDirectory();
File f = new File(sdcard, "/yourfile");
if (!f.exsist()) {
f.createNewFile();
// Use outwriter here, (outputstream) search how to write into a text file in java code
}
I am not able to copy files from my assets folder to the Sd card. How can I accomplish this? Or is there a way to copy files from assets or any other folder to sd card during installation of the app?
Here is my code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CopyAssets();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream("/sdcard/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
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);
}
}
}
You should not hard code storage directory . use Environment.getExternalStorageDirectory()
String destFile = Environment.getExternalStorageDirectory().toString().concat("/ans");
try {
File f2 = new File(destFile);
InputStream in = getAssets().open("try.xml");
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out
.println(ex.getMessage() + " in the specified directory.");
} catch (IOException e) {
System.out.println(e.getMessage());
}
add permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
To write files in the sdcard you have to give the permission on the manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Did you?
Add this code to your onCreate. So the first time your app starts after installation the function to copy assets to SD card and then its never called as you enter the app again.
SharedPreferences score = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor score_inc = score.edit();
int counter = score.getInt("counter",0);
float font_size = score.getFloat("font_size",20.0f);
if(counter==0)
{
//Put your function to copy files here
score_inc.putInt("counter", ++counter);
score_inc.commit();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
I am loading an image from an URL on button click, and storing it as a Bitmap. Now i want to know how to save that downloaded image into sd card as well as in system.
I attempted to do it the following way:
package com.v3.thread.fetchImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class MainThreadActivity extends Activity {
ImageView imView;
EditText ed1;
Bitmap bmImg;
Button bt, btSave;
String imageUrl = "";
int visibilty = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
ed1 = (EditText) findViewById(R.id.edURL);
btSave = (Button) findViewById(R.id.btnSave);
bt = (Button) findViewById(R.id.btnLoad);
bt.setOnClickListener(getImgListener);
imView = (ImageView) findViewById(R.id.imview);
Log.i("img already downloaded", "img");
btSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Log.i("img url", "Under Save");
saveImage();
}
});
}
View.OnClickListener getImgListener = new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
imageUrl = ed1.getText().toString();
if (imageUrl.equals(""))
Toast.makeText(getApplicationContext(), "Enter an URL first", 1000).show();
downloadFile(imageUrl);
Log.i("im url", imageUrl);
btSave.setVisibility(visibilty);
}
};
void downloadFile(String fileUrl) {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Log.i("im connected", "Download");
bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void saveImage() {
File filename;
try {
String path = Environment.getExternalStorageDirectory().toString();
Log.i("in save()", "after mkdir");
new File(path + "/mvc/mvc").mkdir();
filename = new File(path + "/mvc/mvc/var3.jpg");
Log.i("in save()", "after file");
FileOutputStream out = new FileOutputStream(filename);
Log.i("in save()", "after outputstream");
bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Log.i("in save()", "after outputstream closed");
MediaStore.Images.Media.insertImage(getContentResolver(),
filename.getAbsolutePath(), filename.getName(),
filename.getName());
bt.setText("Saved...");
Toast.makeText(getApplicationContext(),
"File is Saved in " + filename, 1000).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Loading of image from URL is working, but when I press the save button to save it, it throws the exception
java.io.FileNotFoundException: /mnt/sdcard/mvc/mvc/var3.image(No such
file or directory)
So how do I save the image to the SD card correctly?
You will need to first create the directories and sub-directories where you want to create the files.
I see that you used the mkdir() method. Try mkdirs(), and it should work.
Add WRITE_EXTERNAL_STORAGE android permission in your Manifest:
Then
BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Get to directory (a File object) from SD Card such as:
File sdCardDirectory = Environment.getExternalStorageDirectory();
Create your specific file for image storage:
File image = new File(sdCardDirectory, "download.png");
Then,
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
//Display Downloaded
} else {
// display Error in Downloading
}
In following code i want to crate a file in sdcard. but it not giving any valid output. showing only the hello world...Where the "file created" message will be displayed and where the file will be stored?
package com.read;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class read extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String FILENAME = "hello_file";
String string = "hello world!";
try{
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}catch(Exception e){}
System.out.println("File created");
}
}
try below code might help you
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.gpx");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("Hello world");
out.close();
}
}catch (IOException e) {
Log.e(TAG, "Could not write file " + e.getMessage());
}
Note: For this to be working your emulator or device must have SDcard
Edit: For reading the file fromSDCard
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Using this method you're trying to create a file in phone's internal memory.
Just use this code:
FileOuputStream fos = new FileOutputStream( "/sdcard/" + FILENAME );
It will create a file in a root folder of your SD card.