I am learning Android and porting my Windows app to Android platform. I need an advice how to download a small text file and read content of this file.
I have following code in my Windows app, I need to rewrite it for Android app:
string contents = "file.txt";
string neturl = "http://www.example.com/file.txt";
HttpClient client = new HttpClient();
try {
HttpResponseMessage message = await client.GetAsync(neturl);
StorageFolder folderForFile = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile fileWithContent = await folderForFile.CreateFileAsync(channels, CreationCollisionOption.ReplaceExisting);
byte[] bytesToWrite = await message.Content.ReadAsByteArrayAsync();
await FileIO.WriteBytesAsync(fileWithContent, bytesToWrite);
var file = await folderForFile.GetFileAsync(contents);
var text = await FileIO.ReadLinesAsync(file);
foreach (var textItem in text)
{
string[] words = textItem.Split(',');
...
I have found what on Android I need to create following class for async download
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("file.txt");
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
// 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;
}
In the code above I try to download file and name it as "file.txt", but get exception 'FileNotFoundException file.txt open failed: EROFS (Read-only file system)", I need to save it internally (I do not want to let users to see this file in the file explorers) and rewrite file if it exists.
And I try to execute this task and read file
void DownloadAndReadContent() {
new DownloadFileFromURL().execute("http://www.example.com/file.txt");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput("file.txt")));
String str = "";
while ((str = br.readLine()) != null) {
Log.d(LOG_TAG, str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
so downloading to SD card is working
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File SDCardRoot = Environment.getExternalStorageDirectory();
SDCardRoot = new File(SDCardRoot.getAbsolutePath() + "/plus");
SDCardRoot.mkdir();
File file = new File(SDCardRoot,"settings.dat");
FileOutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
and reading:
new DownloadFileFromURL().execute("http://www.example.com/file.txt");
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.d(LOG_TAG, "SD n\a " + Environment.getExternalStorageState());
return;
}
File sdPath = Environment.getExternalStorageDirectory();
sdPath = new File(sdPath.getAbsolutePath() + "/plus");
File sdFile = new File(sdPath, "settings.dat");
try {
BufferedReader br = new BufferedReader(new FileReader(sdFile));
String str = "";
while ((str = br.readLine()) != null) {
String[] words = str.split(",");
// do some work
}
}
Log.d(LOG_TAG, str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Related
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
I want to download file(.docx,.pdf,image,or any type) from server.I am using spring-mvc REST API.By Using Resttemplate.exchange(...) i got Response from server in the form of stream but i am unable to parse it.So how should i do that and write into file?
File Return code (server) :
public ResponseEntity<?> downloadFile(..){
if (downloadFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(downloadFile);
return ResponseEntity.ok()
.contentLength(downloadFile.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(newInputStreamResource(fileInputStream));}
else {
return responseEntity.status(HttpStatus.NOT_FOUND)
.body(ErrorMsgWebapiUtil.AUTHORIZED_USER);
}
}
Response from Server:
<200 OK,PNG
������
IHDR����8����û������Þ¢ø������sBIT3���� ��IDATxíÝ?'T����pþÖé������T*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����óÿ��0\§ÁzõK��������IEND®B`
Code At my Android (client) :
try {
mRespEntity = mRestTemplate.exchange(strFinal, HttpMethod.POST, mRequestEntity, String.class);
mResponseCode = mRespEntity.getStatusCode().toString();
if (mResponseCode.equals("200")) {
String outdir = "sdcard/downloads/";
int length = Integer.parseInt(mRespEntity.getHeaders().getContentLength() + "");
inputStream = new BufferedInputStream((InputStream) mRespEntity.getBody()); //Here it Throughs Exception:java.lang.String cannot be cast to java.io.InputStream
byte[] buffer = new byte[length];
int read = 0;
File dFile = new File(outdir, filename);
fos = new DataOutputStream(new FileOutputStream(dFile));
while ((read = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
}
} catch (Exception e) {
if (e != null) {
e.printStackTrace();
Log.e(TAG, "getFileFolderSyncData() Error:" + e.getMessage());
return false;
}
} finally {
// resetSSLFactory();
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
// outputStream.flush();
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
At Line inputStream = new BufferedInputStream((InputStream) mRespEntity.getBody()); here it through exception :"java.lang.String cannot be cast to java.io.InputStream"
Got solution...
public String FileDownload(...){
String url = ....;
String res = ...;
String outdir = ...;
File outputFile = new File(outdir, filename);
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("param1", value);//post parameters
String urlParameters = ...;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
in = new BufferedInputStream(con.getInputStream());
fout = new FileOutputStream(outputFile);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
res = "true";
} else {
res = con.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Exception in file Download:" + e.getMessage());
res = "false";
} finally {
try {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
res = "true";
} catch (IOException e) {
e.printStackTrace();
res = "false";
}
}
return res;
}
protected void doDownload(final String urlLink, final String fileName) {
Thread dx = new Thread() {
public void run() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Content2/");
if(dir.exists()==false) {
dir.mkdirs();
}
//Save the path as a string value
try
{
URL url = new URL(urlLink);
Log.i("FILE_NAME", "File name is "+imageFile);
Log.i("FILE_URLLINK", "File URL is "+url);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir+"/"+imageFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
Log.i("ERROR ON DOWNLOADING FILES", "ERROR IS" +e);
}
}
};
dx.start();
}
through this, I cannot download the file from the server.
How to solve this problem?
First of all you should use Async-Task.
Here is how you can do this
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
i follow more explain in this site for download mp3 or picture from URL , I follow more method and try to write my method but when i run application it stop.
I make method to query download when click
also put permission for INTERNET & WRITE_EXTERNAL_STORAGE
put the problem is still
this method is download
public static void downloadMain(){
File fileToSave = null;
String scrPath ="http://***";
BufferedInputStream bis;
BufferedOutputStream bos;
fileToSave = new File(Environment.getExternalStorageDirectory().getPath() +"/"+ "A"+"/");
if (!fileToSave.exists())
fileToSave.mkdirs();
fileToSave = new File(Environment.getExternalStorageDirectory().getPath() +"/"+ "A" +"/" + "h"+"/");
if (!fileToSave.exists())
fileToSave.mkdirs();
File file = new File (fileToSave,"***.mp3");
try{
URL url = new URL(scrPath+"***.mp3");
URLConnection ucon = url.openConnection();
ucon.connect();
bis=new BufferedInputStream(ucon.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(file));
bis=new BufferedInputStream(url.openStream());
byte[] data = new byte[1024];
int a =0;
while(true){
int k = bis.read(data);
if(k==-1){
bis.close();
bos.flush();
bos.close();
break;
}
bos.write(data, 0, k);
a+=k;
}
}catch(IOException e){}
}
I have three main perplexity about your program:
Do you run the following code in an asynctask? (this must run asincronusly otherwise it will block)
Why it loop infinitly?
You couldn't open an url or a file named with a '*' inside of it
Edit:
You must run the download method asincronusly otherwise it wouldn't work, interaction with filesystem and network couldn't be done in the main thread
Edit2:
AsyncTask should be something like this
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");//put here your path and your mkdirs
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
}
And you shoould call it like this
DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
You could also have a look at this answer
I am trying to fetchg data from server like MP3 files, video files, etc. in my application. The application should show the list of video files received from the server.
How can I do this?
/** this function will download content from the internet */
static int writeData(String fileurl, boolean append, String path,
String filename, Activity mContext) throws CustomException {
URL myfileurl = null;
ByteArrayBuffer baf = null;
HttpURLConnection conn = null;
String mimeType="";
final int length;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) myfileurl
.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setConnectTimeout(100000);
length = conn.getContentLength();
mimeType=conn.getContentType().toString();
System.out.println("Extension..."+mimeType);
if(mimeType.equalsIgnoreCase("application/vnd.adobe.adept+xml") || mimeType.equalsIgnoreCase("text/html; charset=utf-8"))
return 0;
if (length > 0) {
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(1000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((byte) current);
mBufferError=false;
} catch (Exception e){
// TODO: handle exception
mBufferError=true;
e.printStackTrace();
throw new CustomException("### memory problem ", "Buffer Error");
}
}
}
} catch (IOException e) {
mBufferError=true;
e.printStackTrace();
}
try{
if(conn.getResponseCode()==200 && mBufferError==false)
{
path = path + "/" + filename;
boolean appendData = append;
FileOutputStream foutstream;
File file = new File(path);
boolean exist = false;
try {
if (appendData)
exist = file.exists();
else
exist = file.createNewFile();
} catch (IOException e) {
try {
return 1;
} catch (Exception err) {
Log.e("SAX", err.toString());
}
}
if (!appendData && !exist) {
} else if (appendData && !exist) {
} else {
try {
foutstream = new FileOutputStream(file, appendData);
foutstream.write(baf.toByteArray());
foutstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}catch (Exception e) {
// TODO: handle exception
throw new CustomException("### I/O problem ", "I/O Error");
}
return 1;
}
once download complete search the file with extension(.3gp) for video
hope it helps
Check this link,
https://stackoverflow.com/search?q=how+to+download+mp3+%2Cvideos+from+server+in+android
Try this code
url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename" // save in your sdcard
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}
catch (Exception ex)
{
}
and after you want to use MediaPlayer
and create object of mediaplayer in your activity
and play.
mp.reset();
mp.start();