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
Related
I have a resource file in my /res/raw/ folder (/res/raw/textfile.txt) which I am trying to read from my android app for processing.
public static void main(String[] args) {
File file = new File("res/raw/textfile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Do something with file
Log.d("GAME", dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried different path syntax but always get a java.io.FileNotFoundException error. How can I access /res/raw/textfile.txt for processing? Is File file = new File("res/raw/textfile.txt"); the wrong method in Android?
***** Answer: *****
// Call the LoadText method and pass it the resourceId
LoadText(R.raw.textfile);
public void LoadText(int resourceId) {
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Note this will return nothing, but will print the contents line by line as a DEBUG string in the log.
If you have a file in res/raw/textfile.txt from your Activity/Widget call:
getResources().openRawResource(...) returns an InputStream
The dots should actually be an integer found in R.raw... corresponding to your filename, possibly R.raw.textfile (it's usually the name of the file without extension)
new BufferedInputStream(getResources().openRawResource(...)); then read the content of the file as a stream
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();
}
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 want to read a text file that i had write in another activity using OutputStreamWriter.
this is my readFromFile method in Sale.java:
private int readFromFile(String request) {
int res = 0;
try {
//InputStream inputStream = openFileInput("dalassnums.txt");
File file=new File("dalassnums.txt");
InputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null ) {
String s=bufferedReader.readLine();
if(receiveString==request) {
res=Integer.valueOf(s);
break;
}
}
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
res=0;
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return res;
}
And this is writeToFile method in MainActivity.java:
private void writeToFile2(String numchar) {
try {
//File file=new File("dalassnums.txt");
//OutputStream outputStream=new FileOutputStream(file);
OutputStreamWriter outputStreamWriter;
if(numchar=="1") outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_PRIVATE));
else outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_APPEND));
for(int k=0; k<imageNums.size();k+=2){
outputStreamWriter.append(imageNums.get(k));
outputStreamWriter.append("\n");
outputStreamWriter.append(imageNums.get(k+1));
outputStreamWriter.append("\n");
}
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
When performing readFromFile, it returns 0 that means file not found;
I read about passing context but i don't know what context to pass; And wondering if there is any other way than passing context.
Any help would be appreciated.
Use : openFileInput in readFromFile, look here for example:
openFileInput() and/or openFileOutput() i/o streams silently failing
Another problem is that this is invalid:
if(numchar=="1")
you should
if(numchar.equals("1"))
otherwise you compare reference values instead content of string
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 :)