Amazon s3 file download from android - android

I am trying to make a demo app.
That download a image from my s3 server to my phones memory card.
I tried the demo codes and wrote the following. But the app force closes as soon as i run it on my phone.
Any help would be appreciated.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File f=null;
try{
File dir= Environment.getExternalStorageDirectory();
f= new File(dir,"test.jpg");
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Exception", Toast.LENGTH_SHORT).show();
}
AWSCredentials creden=new BasicAWSCredentials(accessKey,secretKey);
AmazonS3Client s3Client=new AmazonS3Client(creden);
ObjectMetadata obj= s3Client.getObject(new GetObjectRequest("adj-temp","funflick_1.jpg"),f);
}

Try this it will work Happy coding
{
String str_FilePathInDevice = "/sdcard/" + "/"
+ "RestoreFolderName" + "/" + "filname.extention";
File file = new File(str_FilePathInDevice);
String str_Path = file.getPath().replace(file.getName(), "");
File filedir = new File(str_Path);
try {
filedir.mkdirs();
} catch (Exception ex1) {
}
S3Object object = s3Client.getObject(new GetObjectRequest(
"BucketName", "keyName"));
BufferedReader reader = new BufferedReader(new InputStreamReader(
object.getObjectContent()));
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
while (true) {
String line = reader.readLine();
if (line == null)
break;
writer.write(line + "\n");
}
writer.flush();
writer.close();
reader.close();
}

Related

Can't read a pdf file on Android downloaded from my back Spring

I can't read with Acrobat Reader a created file.pdf on my Android Studio (pdf is an exemple, I also need .jpg or .txt) because there is an error.
private void uriGetDocumentGedFindById(Integer id, String extension) throws Throwable {
String url = PreferencesFragment.DEFAULT_SERVER_URL_DOCUMENTGEDFINDBYID + id;
MyHttpClient client = new MyHttpClient(url);
URL url2 = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url2.openConnection();
responsUriGetDocumentGedFindById = client.getResponseHttpURLConnection(urlConnection);
String name = id.toString() + "." + extension;
saveFile(responsUriGetDocumentGedFindById, name, PreferencesFragment.DOCUMENTS_FOLDER);
}
public void saveFile(String json, String name, String path) throws IOException {
try {
FileWriter writer = new FileWriter(
new File(mContext.getFilesDir().toString() + path, name));
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponseHttpURLConnection(HttpURLConnection urlConnection) {
StringBuffer response = null;
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
I receive this from my back : via Postman on the left (this is functional, I can read the pdf), in my file.pdf (on Android Studio) on the right (there is an error with Acrobat Reader)
So first I can't read my file.pdf and second the file.pdf is bigger than the original whitout any additional information (original 200Ko and my file.pdf 400Ko) this is perhaps a clue...
My back :
#Override
public ResponseEntity<Resource> findByIdDocumentGed(Integer id) throws FileNotFoundException {
DocumentGed documentGed = documentGedService.findByIdDocumentGed(id);
InputStreamResource resource = null;
try {
Integer idFile = documentGed.getFichierCourant().getId();
String extensionFile = documentGed.getFichierCourant().getTypeFichier().getExtension();
File file = new File(nasIris + "/ged/import/" + idFile + "." + extensionFile);
resource = new InputStreamResource(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (resource == null) {
return new ResponseEntity<>(resource, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(resource, new HttpHeaders(), HttpStatus.OK);
}
Have you tried to use FileOutputStream instead FileWriter ?

Download a file with an AsyncTask

I tried using many codes I've found for downloading files with an AsyncTask with no success yet.
I get an error on the logcat: E/Error:: No such file or directory.
Despite looking for solutions for this error, couldn't find What's missing or wrong.
This is the doInBackground method in which I assume something is missing/wrong:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new DownloadJSON().execute("http://api.androidhive.info/json/movies.json");
}
protected String doInBackground(String...fileUrl) {
int count;
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(fileUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File fileName = new File(root+"/movies.json");
boolean existsOrNot = fileName.createNewFile(); // if file already exists will do nothing
// Output stream to write file
OutputStream output = new FileOutputStream(fileName,false);
byte data[] = new byte[1024];
System.out.println("Downloading");
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Thanks.
Didn't want to bombard with redundant code. If some other code is needed, I'd love to provide it.
UPDATED ANSWER
this is working for me, write file in local storage and read it again on method PostExecute
class DownloadJSON extends AsyncTask<String, Void, Void>{
String fileName;
String responseTxt;
String inputLine;
String folder;
#Override
protected Void doInBackground(String... strings) {
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//Set methods and timeouts
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder response = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
response.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
responseTxt = response.toString();
Log.d(TAG, "doInBackground: responseText " + responseTxt);
// PREPARE FOR WRITE FILE TO DEVICE DIRECTORY
FileOutputStream fos = null;
fileName = "fileName.json";
folder = fileFolderDirectory();
try {
fos = new FileOutputStream(new File(folder + fileName));
//fos = openFileOutput(folder + fileName, MODE_PRIVATE);
fos.write(responseTxt.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
fos.close();
}
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// -- THIS METHOD IS USED TO ENSURE YOUR FILE AVAILABLE INSIDE LOCAL DIRECTORY -- //
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(folder +fileName));
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
Toast.makeText(TestActivity.this, "result " + sb.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ops, almost forget this method
public static String fileFolderDirectory() {
String folder = Environment.getExternalStorageDirectory() + File.separator + "write_your_app_name" + File.separator;
File directory = new File(folder);
if(!directory.exists()){
directory.mkdirs();
}
return folder;
}
Your root is wrong
String root = "data/data/package.appname";
make sure your root contains right package name or file path.
package name which should be your application id

Write /Read String Array to File in Android, using internal or external storage whichever is available

I am downloading a json response array string from network and displaying a listview using this data.I want to store this response for first time in a file stored under internal/external storage, so i dont have to download the data again in future.
How can i store this response in a internal/external storage file and read it later when my application starts afresh again.And File should be created first time only and later when application is started again, a check to whether file exists or not should be in place.
Any examples /utility class where this has been done?
Here is my code...
The Problem with this code is...it always creates a new directory and a new file.
public class FileCache {
static File cacheDir;
static final String DIRECTORY_ADDRESS = "/Android/data/com.example.savefiletostoragedemo/.newDirectory";
static final String TAG="DEMO";
public static void createDirectory(Context context){
Log.i(TAG,"createDirectory() called...");
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
cacheDir = new File(Environment.getExternalStorageDirectory(),DIRECTORY_ADDRESS);
Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.exists());
}
else{
cacheDir=context.getCacheDir();
Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.exists());
}
if(!cacheDir.exists()){
cacheDir.mkdirs();
Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
}
else{
Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
}
}
public static File getFile(String filename){
//String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public static void saveFile(String dataToWrite, File file){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.write(dataToWrite);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static String readFromFile(File file){
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
bufferedReader.close();
inputStreamReader.close();
return stringBuilder.toString();
}
catch (FileNotFoundException e) {
} catch (IOException e) {
}
return null;
}
public static void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
I call createDirectory() in Application class
MainActivity.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadUrsl().execute(null,null,null);
}
private class DownloadUrsl extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... arg0) {
File f = getJson("LISTVIEWDATA");
//String jsonString =FileCache.readFromFile(f);
//Log.i("DEMO", "DATA Read from file is:[ "+jsonString+" ]")
return null;
}
private File getJson(String filename) {
File f = FileCache.getFile(filename);
if(f != null && f.isFile()) {
String jsonString =FileCache.readFromFile(f);
Log.i("DEMO", "DATA Read from file is:[ "+jsonString+" ]");
return f;
}
try {
Log.i("DEMO", "Starting data download...");
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
URI uri = new URI("");
HttpResponse httpResponse = httpclient.execute(new HttpGet(uri));
String response =EntityUtils.toString(httpResponse.getEntity());
Log.i("DEMO", "DATA Received from net is:[ "+response+" ]");
JSONArray array=new JSONArray(response);
FileCache.saveFile(array.toString(), f);
return f;
} catch (Exception ex) {
return null;
}
}
}
Issues with this Code: This code always creates a new directory when application starts...And also creates a new file everytime the data is requested.I also tried isDirectory(), didnt work.
here is how i did it.. Thank you guys For Your Help..:)
public static void createDirectory(Context context){
Log.i(TAG,"createDirectory() called...");
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
cacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.isDirectory());
}
else{
cacheDir=context.getCacheDir();
Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.isDirectory());
}
if(!cacheDir.isDirectory()){
cacheDir.mkdirs();
Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
}
else{
Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
}
}
public static File getFile(String filename){
//String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, String.valueOf(filename.hashCode()));
return f;
}
public static void saveFile(String dataToWrite, File file){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.write(dataToWrite);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static String readFromFile(File file){
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
bufferedReader.close();
inputStreamReader.close();
return stringBuilder.toString();
}
catch (FileNotFoundException e) {
} catch (IOException e) {
}
return null;
}
private static final String cacheDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + MyUtilClass.class.getPackage().getName();
public static void cacheResponse(String name, List<String> data) throws IOException {
File f = new File(cacheDir + "/" + name);
if (f.exists())
return;
Writer fw = new FileWriter(f);
for (String line : data) {
fw.write(line);
}
fw.close();
}

extend Android.util.Log to write to file

I would like to extend the android.util.Log class to also write to a log file in internal storage of the device, preferrably also for specific TAGS.
I currently have an implementation:
public class CustomLogger{
private final static Logger fileLog = Logger.getLogger(MainActivity.class);
private Context context;
public CustomLogger(Context c){
this.context = c;
final LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(context.getFilesDir() + File.separator + "myApp.log");
logConfigurator.setRootLevel(Level.DEBUG);
logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.configure();
}
public void i(String TAG, String message){
// Printing the message to LogCat console
Log.i(TAG, message);
// Write the log message to the file
fileLog.info(TAG+": "+message);
}
public void d(String TAG, String message){
Log.d(TAG, message);
fileLog.debug(TAG+": "+message);
}
}
As you can see this custom logger logs both to a log file on the internal storage (using the android-logging-log4j library) and through the android.util.Log class.
However i would like the standard log entries from the android.util.Log class in my log file, and if possible only certain (custom) TAGS.
Anybody has an example or any good tips on how to reach this?
Thanks in advance
You can read log cat programmatically and store into text file or you send it wherever you want.
Below is the detailed article I have written for same:
Read & Store Log-cat Programmatically in Android
And for reading the logcat here is sample code:
public class LogTest extends Activity {
private StringBuilder log;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(log.toString());
} catch (IOException e) {
}
//convert log to string
final String logString = new String(log.toString());
//create text file in SDCard
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
dir.mkdirs();
File file = new File(dir, "logcat.txt");
try {
//to write logcat in text file
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(logString);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So there is much shorter variant
try {
final File path = new File(
Environment.getExternalStorageDirectory(), "DBO_logs5");
if (!path.exists()) {
path.mkdir();
}
Runtime.getRuntime().exec(
"logcat -d -f " + path + File.separator
+ "dbo_logcat"
+ ".txt");
} catch (IOException e) {
e.printStackTrace();
}

Writing/Reading Files to/from Android phone's internal memory

I have an utility class named 'MyClass'. The class has two methods to read/write some data into phone's internal memory. I am new to android, Please follow below code.
public class MyClass {
public void ConfWrite() {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
while executing ConfWrite method, it fails
please provide a better solution to solve this
thanks in advance
You can Read/ Write your File in data/data/package_name/files Folder by,
To Write
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
To Read
BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(getFilesDir()+File.separator+"MyFile.txt")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = bufferedReader.readLine()) != null){
builder.append(read);
}
Log.d("Output", builder.toString());
bufferedReader.close();
public static void WriteFile(String strWrite) {
String strFileName = "Agilanbu.txt"; // file name
File myFile = new File("sdcard/Agilanbu"); // file path
if (!myFile.exists()) { // directory is exist or not
myFile.mkdirs(); // if not create new
Log.e("DataStoreSD 0 ", myFile.toString());
} else {
myFile = new File("sdcard/Agilanbu");
Log.e("DataStoreSD 1 ", myFile.toString());
}
try {
File Notefile = new File(myFile, strFileName);
FileWriter writer = new FileWriter(Notefile); // set file path & name to write
writer.append("\n" + strWrite + "\n"); // write string
writer.flush();
writer.close();
Log.e("DataStoreSD 2 ", myFile.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readfile(File myFile, String strFileName) {
String line = null;
try {
FileInputStream fileInputStream = new FileInputStream(new File(myFile + "/" + strFileName)); // set file path & name to read
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // create input steam reader
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) { // read line by line
stringBuilder.append(line + System.getProperty("line.separator")); // append the readed text line by line
}
fileInputStream.close();
line = stringBuilder.toString(); // finially the whole date into an single string
bufferedReader.close();
Log.e("DataStoreSD 3.1 ", line);
} catch (FileNotFoundException ex) {
Log.e("DataStoreSD 3.2 ", ex.getMessage());
} catch (IOException ex) {
Log.e("DataStoreSD 3.3 ", ex.getMessage());
}
return line;
}
use this code to write --- WriteFile(json); // json is a string type
use this code to read --- File myFile = new File("sdcard/Agilanbu");
String strObj = readfile(myFile, "Agilanbu.txt");
// you can put it in seperate class and just call it where ever you need.(for that only its in static)
// happie coding :)

Categories

Resources