i have build an application the user can download with one button click an image and attachments text file (in two separate folder one folder for store image and the other for text file )
now I would like build an listview for display this data, each row contain image (ImageView) and name of image (textView) and when user click on it i would like display the attachments text file
DownloadFile code :
#Override
protected Void doInBackground(String... strings) {
String filetxtUrl = strings[0];
String filetxtName = strings[1];
String fileImageUrl = strings[2];
String fileImageName = strings[3];
String extStorageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); //(Environment.DIRECTORY_DOWNLOADS)
File folder = new File(extStorageDirectory, "folder");
if (!folder.exists()) {
folder.mkdirs();
}
File folder1 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"
+ "folder" , "txt");
if (!folder1.exists()) {
folder1.mkdirs();
}
File TxtFile = new File(folder1, filetxtName);
File folder3 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"
+ "folder" , "Image");
if (!folder3.exists()) {
folder3.mkdirs();
}
File ImageFile = new File(folder3, fileImageName);
try{
TxtFile.createNewFile();
ImageFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(filetxtUrl, TxtFile);
FileDownloader.downloadFile(fileImageUrl, ImageFile);
L.m("File Download successufuly in Sdcard0 ");
return null;
}
FileDownloader code :
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
L.m(""+e);
} catch (MalformedURLException e) {
L.m(""+e);
} catch (IOException e) {
L.m(""+e);
}
}
}
I want use the code below to read the the txt files attachment
public void displayOutput()
{
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/TextFile.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"File not found!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
TextView output=(TextView) findViewById(R.id.output);
// Assuming that 'output' is the id of your TextView
output.setText(text);
}
Related
I am currently developing an application that reads,writes,updates,deletes json file.i have 4 json files namely data.json(to store name,address,area,pin),image.json(to store image name),location.json(to store latitute,longitude) and final.json that merges the above json files.final.json will combine all data from 3 files to make a single record.In a activity I need to read the name,date,time of all records stored in final.json in different radio buttons. I am unable to read only the name,date,time from a record stored in temp.json as temp.json contains latitute,longitude,image name,name,address,pin,area,date,time.Please help me do the following.Also I need to delete only specific record from temp.json file.
This is the code I used to read the text from temp.json.How to read only name,date,time from the file.I am able to read all the parameters
My temp.json looks like
{Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22"]} {Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22" ]}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File file = new File(myDir, FILENAME);//making a new file in the folder
if(file.exists()) // check if file exist
{
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Set the text
String x=text.toString();
String z=x.replace("{","").replace("date:","").replace("time:","").replace("Record:","").replace("[","").replace("latitude:","").replace("longitude:","").replace("name:","").replace("address:","").replace("pin:","").replace("area:","").replace("image:","").replace("\"","").replace("]","").replace("}","");
String[] y=z.split(",");
//rb1.setText(y[3].toString()+","+y[7].toString()+","+y[8].toString()+""+"");
// rb2.setText(y[11].toString()+","+y[15].toString()+","+y[16].toString());
//rb3.setText(y[19].toString()+","+y[23].toString()+","+y[24].toString());
//rb4.setText(y[27].toString()+","+y[31].toString()+","+y[32].toString());
}
else
{
rb1.setText("Sorry file doesn't exist!!");
}
///////merge code////
static class CopyFileContent {
public static void main(String[] args) {
JSONObject jsonObj2 = new JSONObject();
try {
// Here we convert Object to JSON
jsonObj2.put("date",a.toString());jsonObj2.put("time",c.toString());// Set the first name/pair
} catch (JSONException ex) {
ex.printStackTrace();
}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File destFile = new File(myDir, FILENAME11);//making a new file in the folder
/* Source file, from which content will be copied */
File sourceFile1 = new File(myDir,FILENAME12);
File sourceFile2 = new File(myDir,FILENAME13);
File sourceFile3 = new File(myDir,FILENAME14);
/* destination file, where the content to be pasted */
// File destFile = new File(FILENAME);
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream input1 = null;
InputStream input2 = null;
InputStream input3 = null;
OutputStream output = null;
InputStream input4=null;
try {
/* FileInputStream to read streams */
input1 = new FileInputStream(sourceFile1);
input2 = new FileInputStream(sourceFile2);
input3 = new FileInputStream(sourceFile3);
/* FileOutputStream to write streams */
output = new FileOutputStream(destFile,true);
byte[] buf = new byte[1024];
int bytesRead;
output.write("{Record:[".getBytes());
while ((bytesRead = input1.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input2.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input3.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
output.write(jsonObj2.toString().getBytes());
output.write("]}".getBytes());
output.write("\r\n".getBytes());
output.write("\r\n".getBytes());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (null != input1) {
input1.close();
}
if (null != input2) {
input2.close();
}
if (null != input3) {
input3.close();
}
if (null != output) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
We are working on android application,in which mp3 files should be downloaded into internal storage in a background service. We have implemented this using with code snippet mentioned below inside an intent service,But when we try to play the mp3 we are getting an error,like player is not supporting this audio file. If any one has a solution for this issue,Please advise me for the same.
Code Snippet:
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
// String fileName = Environment.getExternalStorageDirectory().toString() + "/trail.mp3";
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
File dir = new File(output.getAbsolutePath()
+ "/TRIALS/");
dir.mkdirs();
String path = dir + "/" +"trail" + ".mp3";
File f = new File(path);
if (f.exists()) {
f.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
//URL url = new URL(urlPath);
InputStream input = new BufferedInputStream(url.openStream());
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(f.getPath());
byte data[] = new byte[lenghtOfFile];
long total = 0;
int times = -1;
while ((times = reader.read()) != -1) {
fos.write(times);
}
// Successful finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
1.Check if urlPath is correct.You can open it by explorer and check if a .mp3 begins to be downloaded.
2.Compare size of the file that you get by explorer to the one that downloaded through your code.
3.If the sizes differ,that means download failure.Try to modify your code like this:
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
File dir = new File(output.getAbsolutePath()
+ "/TRIALS/");
dir.mkdirs();
String path = dir + "/" +"trail" + ".mp3";
File f = new File(path);
if (f.exists()) {
f.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
URLConnection urlcon = url.openConnection();
stream = urlcon.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(f.getPath());
int times = -1;
while ((times = reader.read()) != -1) {
fos.write(times);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I remove some useless code and add fos.flush() before fos.close().
I am a newbie working with Android. A file is already created in the location data/data/myapp/files/hello.txt; the contents of this file is "hello". How do I read the file's content?
Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
To read data from internal storage you need your app files folder and read content from here
String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );
Also you can use this approach
FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
Read a file as a string full version (handling exceptions, using UTF-8, handling new line):
// Calling:
/*
Context context = getApplicationContext();
String filename = "log.txt";
String str = read_file(context, filename);
*/
public String read_file(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
Note: you don't need to bother about file path only with file name.
Call To the following function with argument as you file path:
private String getFileContent(String targetFilePath) {
File file = new File(targetFilePath);
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
Log.e("", "" + e.printStackTrace());
}
StringBuilder sb;
while (fileInputStream.available() > 0) {
if (null == sb) {
sb = new StringBuilder();
}
sb.append((char) fileInputStream.read());
}
String fileContent;
if (null != sb) {
fileContent = sb.toString();
// This is your file content in String.
}
try {
fileInputStream.close();
} catch (Exception e) {
Log.e("", "" + e.printStackTrace());
}
return fileContent;
}
String path = Environment.getExternalStorageDirectory().toString();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: " + file.length);
for (int i = 0; i < file.length; i++) {
//here populate your listview
Log.d("Files", "FileName:" + file[i].getName());
}
I prefer to use java.util.Scanner:
try {
Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
String result = sb.toString();
} catch (IOException e) {}
For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE
try {
FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
fos.write(csv.getBytes());
fos.close();
File file = Main.this.getFileStreamPath("exported_data.csv");
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
Hi i have a string that contains html and css that i want to load into a WebView as a file. so i want to create a Directory on the internal storage i don't really want to store it on an SDCard as the file i'm saving contains important information. I then want to create a mFile.html not that directory. And the final step is then return the file to load into a WebView. Does anyone know how to do this?
heres what i have tried so far
public static void writeFileToDirectory(Context activityContext, String writableString,String folderName, String fileName){
File myDir = activityContext.getFilesDir();
try {
File secondFile = new File(myDir + "/" + folderName + "/", fileName);
if (secondFile.getParentFile().mkdirs()) {
secondFile.createNewFile();
FileOutputStream fos = new FileOutputStream(secondFile);
fos.write(writableString.getBytes());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File secondInputFile = new File(myDir + "/html/", fileName);
InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile));
BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
secondInputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
try this
File myDir = activityContext.getFilesDir();
try {
File secondFile = new File(myDir + "/" + folderName);
if(!secondFile.exists())
{
secondFile.mkdir();
}
FileOutputStream fos = new FileOutputStream(secondFile.getAbsolutePath()+"/"+fileaName);
fos.write(writableString.getBytes());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
i have An Error while download PDF file From Server and save it on SD
i have permission To Access internet and external storage ..
It`s working fine on android 2.3.6
But on Tab 4.1.1 its create the file with 0 byte
URL url = new URL("https://docs.google.com/"+direct);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "application/xml");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/folder/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,book.getBook_name()+".pdf");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
publishProgress((downloadedSize*100)/totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try this:
private String getExternalSDPath() {
File file = new File("/system/etc/vold.fstab");
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
// handle
}
String path = null;
try {
if (fr != null) {
br = new BufferedReader(fr);
String s = br.readLine();
while (s != null) {
if (s.startsWith("dev_mount")) {
String[] tokens = s.split("\\s");
path = tokens[2]; // mount_point
if (Environment.getExternalStorageDirectory()
.getAbsolutePath().equals(path)) {
break;
}
}
s = br.readLine();
}
}
} catch (IOException e) {
// handle
} finally {
try {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
// handle
}
}
return path;
}
The code is made specifically for Samsung Devices with both internal, an internal that acts as external, and SD.
I needed to access the SD and came up with the above code, so you can try it and possibly modify it to work on all devices.
Edit: My download AsyncTask
private class DownloadFile extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String filename = "somefile.pdf";
HttpURLConnection c;
try {
URL url = new URL("http://someurl.com/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file= new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
} else {
return "Unable to create folder";
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
super.onPostExecute(result);
}
}