I am using http://www.siegmann.nl/epublib to read epub file. My code is mentioned below.
try {
book = epubReader.readEpub(new FileInputStream("/sdcard/EpubTesting.epub"));
Resource res;
Spine contents = book.getSpine();
List<SpineReference> spinelist = contents.getSpineReferences();
StringBuilder string = new StringBuilder();
String line = null;
int count = spinelist.size();
for (int i=0;i<count;i++){
res = contents.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = (string.append(line+"\n")).toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(linez);
s1.loadDataWithBaseURL("/sdcard/",linez, "text/html", "UTF-8",null);
}catch (FileNotFoundException e) {
Toast.makeText(mContext, "File not found.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(mContext, "IO Exception.", Toast.LENGTH_SHORT).show();
}
Also tried
s1.loadDataWithBaseURL("",linez, "text/html", "UTF-8",null);
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
But result is sifar. Please tell me what I have to do to show the contained images in file. I have gone through FAQ says Make a subclass of android.webkit.WebView that overloads the loadUrl(String) method in such a way that it loads the image from the Book instead of the internet. But till I don't where they extract the file how can I locate the path. Please tell me. I am very confused. Thanks in advance.
public class EpubBookContentActivity extends Activity{
private static final String TAG = "EpubBookContentActivity";
WebView webview;
Book book;
int position = 0;
String line;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
AssetManager assetManager = getAssets();
String[] files;
try {
files = assetManager.list("books");
List<String> list =Arrays.asList(files);
if (!this.makeDirectory("books")) {
debug("faild to make books directory");
}
copyBookToDevice(list.get(position));
String basePath = Environment.getExternalStorageDirectory() + "/books/";
InputStream epubInputStream = assetManager.open("books/"+list.get(position));
book = (new EpubReader()).readEpub(epubInputStream);
DownloadResource(basePath);
String linez = "";
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
linez = linez.replace("../", "");
// File file = new File(Environment.getExternalStorageDirectory(),"test.html");
// file.createNewFile();
// FileOutputStream fileOutputStream = new FileOutputStream(file);
// fileOutputStream.write(linez.getBytes());
// fileOutputStream.close();
webview.loadDataWithBaseURL("file://"+Environment.getExternalStorageDirectory()+"/books/", linez, "text/html", "utf-8", null);
} catch (IOException e) {
Log.e("epublib exception", e.getMessage());
}
}
public boolean makeDirectory(String dirName) {
boolean res;
String filePath = new String(Environment.getExternalStorageDirectory()+"/"+dirName);
debug(filePath);
File file = new File(filePath);
if (!file.exists()) {
res = file.mkdirs();
}else {
res = false;
}
return res;
}
public void debug(String msg) {
// if (Setting.isDebug()) {
Log.d("EPub", msg);
// }
}
public void copyBookToDevice(String fileName) {
System.out.println("Copy Book to donwload folder in phone");
try
{
InputStream localInputStream = getAssets().open("books/"+fileName);
String path = Environment.getExternalStorageDirectory() + "/books/"+fileName;
FileOutputStream localFileOutputStream = new FileOutputStream(path);
byte[] arrayOfByte = new byte[1024];
int offset;
while ((offset = localInputStream.read(arrayOfByte))>0)
{
localFileOutputStream.write(arrayOfByte, 0, offset);
}
localFileOutputStream.close();
localInputStream.close();
Log.d(TAG, fileName+" copied to phone");
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
Log.d(TAG, "failed to copy");
return;
}
}
private void DownloadResource(String directory) {
try {
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
Log.d(TAG, rs.getHref());
File oppath1 = new File(directory, rs.getHref().replace("OEBPS/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
System.out.println("Path : "+oppath1.getParentFile().getAbsolutePath());
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, rs.getHref());
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
}
}
}
For that you have to download all resources of epub files (i.e. images,stylesheet) in location where you downloaded .epub file in sdcard. please check below code to download images and css files from .epub files itself using epublib.
for that u have to send parameter of File objects where you want to store those images.
private void DownloadResource(File FileObj,String filename) {
try {
InputStream epubis = new FileInputStream(FileObj);
book = (new EpubReader()).readEpub(epubis);
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
File oppath1 = new File(directory, "Images/"
+ rs.getHref().replace("Images/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, "Styles/"
+ rs.getHref().replace("Styles/", ""));
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
Log.v("error", e.getMessage());
}
}
after this use this your code to set path of images in webview.
if stored in sd card then
s1.loadDataWithBaseURL("file:///sdcard/",linez, "text/html",null,null);
or
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
if in internal storage then
s1.loadDataWithBaseURL("file:///data/data/com.example.project/app_mydownload/",linez, "text/html",null,null);
Related
I simply want to download mp4 or .3gp files from server to android device. I have tried multiple ways to achieve but in some cases it gives IOException and some time give ProtocolException
First Method to download Video using DownloadVideoTask.class
public class DownloadVideoTask extends AsyncTask<String, Integer, Boolean>
{
String nameOfSong;
Context context;
Boolean flage = true;
ProgressDialog progressDialog2;
#SuppressLint("InlinedApi")
public DownloadVideoTask(Context context,String trackTitle)
{
this.context = context;
nameOfSong = trackTitle;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
progressDialog2 = new ProgressDialog(context, AlertDialog.THEME_HOLO_LIGHT);
}
else
{
progressDialog2 = new ProgressDialog(context);
}
progressDialog2.setIndeterminate(false);
progressDialog2.setMax(100);
progressDialog2.setTitle("Please wait...");
try
{
progressDialog2.setMessage("Downloding.. " + nameOfSong.substring(0, 20));
}
catch (Exception e)
{
progressDialog2.setMessage("Downloding Song...." );
}
progressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog2.show();
}
#Override
protected Boolean doInBackground(String... params)
{
/* String trackTitle = params[0];
nameOfSong = trackTitle;
*/
String trackUrl = params[0];
try
{
File root;// = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
root = Environment.getExternalStorageDirectory();
}
else
{
root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
File dir = new File(root.getAbsolutePath() + "/XarDownloder");
if (dir.exists() == false)
{
dir.mkdirs();
}
URL url = new URL(trackUrl);
File file = new File(dir, nameOfSong);
URLConnection urlConnection = url.openConnection();
int fileLength = urlConnection.getContentLength();//ye statement inputStream k bad likhi thi
InputStream inputStream = urlConnection.getInputStream();
OutputStream outputStream = new FileOutputStream(
root.getAbsolutePath() + "/XarDownloder/" + nameOfSong
+ ".mp4");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
try
{
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
else
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))));
}
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.fromFile(file)));
}
catch (Exception e)
{
}
return true;
}
catch (IOException e)
{
flage = false;
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if (result)
{
try
{
Toast.makeText(context,
nameOfSong.substring(0, 30) + "Downloaded...",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(context,
"Song Downloaded...",
Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(context, "Sorry, song is not downloadable",
Toast.LENGTH_LONG).show();
}
progressDialog2.dismiss();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progressDialog2.setProgress(values[0]);
}
}
Second Method using DownloadFile
public class DownloadFile extends AsyncTask<String, Integer, String>
{
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
public DownloadFile()
{
}
#Override
protected String doInBackground(String... params)
{
int count;
try
{
mp4load(videoToDownload);
}
catch (Exception e)
{
// TODO: handle exception
}
/*try
{
URL url = new URL(videoToDownload);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/xarwere/firstdownload.mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
}*/
return null;
}
public void mp4load(String urling)
{
try
{
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
//Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "test.mp4";
File outputFile = new File(file, fileName);
if (!outputFile.exists())
{
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();//my doctory
InputStream is = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (ProtocolException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
Where videoToDownload in DownloadFile.class is the URLi want to download. but at inputStream it gives exception.
And I call these AsyncTask like
new DownloadFile().execute();
new DownloadVideoTask(TestingActivity.this, "nameofsong").execute("http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4");
I slighthly modified your code, but it downloads the file well. Did you add the internet permission?
public class DownloadFile extends AsyncTask<String, Integer, String> {
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
#Override
protected String doInBackground(String... params) {
int count;
try {
mp4load(videoToDownload);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
public void mp4load(String urling) {
try {
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = "test.mp4";
File outputFile = new File(downloadsPath, fileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();
InputStream is = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm not able to understand these classes. I've been trying to create a new file in a new directory on my internal storage, put some text in it and then to read it out. This does not seem to work without the ContextWrapper. So I tried this:
public class DownloadActivity extends Activity {
...
class Download extends AsyncTask<String, Void, String>{
....
private void searchAndSave(String s) throws IOException {
....
ContextWrapper cw = new ContextWrapper(getBaseContext());
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
File fileInFolder = new File(folder, "fileInFolder");
String string = "Hello world!";
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
File fl = new File(cw.getDir("folder", Context.MODE_PRIVATE)+"/fileInFolder");
FileInputStream fin = new FileInputStream(fl);
BufferedReader reader = new BufferedReader(
new InputStreamReader(fin));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
String result = sb.toString();
reader.close();
fin.close();
}
}
Creating the file does not work without the ContextWrapper. I've been reading a lot, but I still have problems to understand, what the Context and the Contextwrapper actually do and why I need them to create a file. Additionally in my code the creating of the FileInputStream does not work. When the program reaches
FileInputStream fin = new FileInputStream(fl);
I always get the error:
05-21 11:18:25.721: W/System.err(7344): java.io.FileNotFoundException:
/data/data/com.example.dice/app_folder/fileInFolder: open failed:
ENOENT (No such file or directory)
I really would appreciate some help with understanding and solving this problem.
UPDATE: I made a more spare Activity, maybe now it's easier to reconstruct the whole thing. (Should I have done this in a new answer, or is it okay to edit my first posting?) Even though I don't get an error message when trying to create a file, is doesn't seem to work. Here I try reading the "Hello world" string, but I get a FileNotFoundException (EISDIR). Just for you to know :)
public class FolderActivity extends Activity {
public final static String TAG = "FolderActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_folder);
Button button = (Button) findViewById(R.id.button_folder);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
folder();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void folder() throws IOException{
Log.d(TAG, "folder");
ContextWrapper cw = new ContextWrapper(getBaseContext());
Log.d(TAG, "cw = new ContextWrapper");
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
Log.d(TAG, "folder = cw.getDir");
File fileInFolder = new File(folder, "fileInFolder");
Log.d(TAG, "fileInFolder = new File");
/*Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());*/
String string = "Hello world!";
// Aksioms suggestion
if (!fileInFolder.exists() && !fileInFolder.mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder);
} else { Log.d(TAG, "file created"); }
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());
String s = fileInFolder.getAbsolutePath();
try {
getStringFromFile(s);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
}
You are trying to open a file which does not exists.
Make sure that you check and create the file if it does not exsist:
if (!fl.exists() && !fl.mkdirs()) {
Log.e("file", "Couldn't create file " + fl);
}
EDIT:
Yes the getDir creats the folder if it is not created.
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
But the problem is here
File fileInFolder = new File(folder, "fileInFolder");
String string = "Hello world!";
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
In here you try to open a file that does not exsist, you just constructed a new file named fileInFolder, but you actually do not have that folder yet.
Try to use the code that I wrote at the first place, before the openFileOutput("fileInFolder", Context.MODE_PRIVATE); :
if (!fileInFolder.exists() && !fileInFolder.mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder);
}
Try this and tell me how it goes.
EDIT 2:
OK I found the problem it was so obvious. The mistake was that we created the fileInFolder as a directory, and you can not write anything there :D
What we should have done is this:
Remove my code for creating the fileInFolder.
if (!fileInFolder .exists() && !fileInFolder .mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder );
} else {
Log.d(TAG, "file created");
}
we do not need to create it because we will use it as a file. So the change I have made in your code is this:
FileOutputStream outputStream = new FileOutputStream(fileInFolder);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream));
out.write(string);
out.close();
Add this between the line String string = "Hello world!"; and the first Log.d... This is the correct way to write in a file.
The whole code:
public class MainActivity extends Activity {
public final static String TAG = "FolderActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button_folder);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
folder();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void folder() throws IOException {
Log.d(TAG, "folder");
ContextWrapper cw = new ContextWrapper(getBaseContext());
Log.d(TAG, "cw = new ContextWrapper");
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
Log.d(TAG, "folder = cw.getDir");
File fileInFolder = new File(folder, "fileInFolder");
Log.d(TAG, "fileInFolder = new File");
/*
* Log.d(TAG, "fileInFolder.getAbsolutePath()" +
* fileInFolder.getAbsolutePath());
*/
String string = "Hello world!";
FileOutputStream outputStream = new FileOutputStream(fileInFolder);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream));
out.write(string);
out.close();
Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());
String s = fileInFolder.getAbsolutePath();
try {
getStringFromFile(s);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getStringFromFile(String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
// Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}}
Check if you have this permission in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I hope everything is clear now.
I am working on an app where I need to save/read my files from Internal storage.
But it read all my data in the same TextView.
Can someone show me show,how to show the data in 2 textviews, or to show me how put the one data under the other data.
Here is my code for saving data:
private void SaveMode() {
String FILENAME ;
String Strin1= textview1.getText().toString();
String String2= textview2.getText().toString();
EditText filename1 = (EditText) findViewById(R.id.filename);
FILENAME = filename1.getText().toString();
if (FILENAME.contentEquals("")){
FILENAME = "UNTITLED";
}
String1 = textview1.getText().toString();
String2= textview2.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("Strin1.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
And here is my code for read my data:
private void getFilenames() {
String[] filenames = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
spinner.setAdapter(filenameAdapter);
}
public void SpinnerClick(View v) {
String selectFile = String.valueOf(spinner.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
showData = (TextView) findViewById(R.id.show_data);
TextView showData1 = (TextView) findViewById(R.id.show_data1);
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
}
EDIT
I tried to edit my read code like this, but with no luck
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
String[] strArray = value.split(";");
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
Edit 2
Got it to work with Shobhit Puri codes
First while saving your data you might insert a delimiter in between those two string. Make sure that delimiter is not the one expected in your textViews.
While saving:
String string3 = ";";
try {
fos.write("Strin1.getBytes());
fos.write("String3.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
Then when you are trying to read it into value string, then split is using .split function. Eg:
String[] strArray = value.split(";");
strArray[0] will give first textview's sting and strArray[1] will give the second.
Update
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
try
{
FileInputStream fis = new FileInputStream(myInternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);
following is my code,
From Activity class
Intent intent = new Intent(this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.setData(Uri.parse("http://www.abc.ezy.asia/E-MobApps/op.apk"));
intent.putExtra("urlpath", "http://www.abc.ezy.asia/E-MobApps/op.apk");
startService(intent);
I have overrided Service Class method onHandle Event
// DownloadService Class
#Override
protected void onHandleIntent(Intent intent) {
Uri data = intent.getData();
String urlPath = intent.getStringExtra("urlpath");
String fileName = data.getLastPathSegment();
File output = new File(Environment.getExternalStorageDirectory(),fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
fos = new FileOutputStream(output.getPath());
byte dataB[] = new byte[1024];
InputStreamReader reader = new InputStreamReader(stream);
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
fos.flush();
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();
}
}
}
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
}
In above code I used File Streams & Input stream reader for downloading
when tried to download html file then complete file was downloaded to my sdcard.But when I tried for APK. The File downloaded of 2.2 mb instead of 2.4 mb Parsing problem is there. Kindly help me to resolve the issue.
try this piece of code :
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(output.getPath());
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
input.close();
result = Activity.RESULT_OK;
I want to save a file to the internal storage by getting the text inputted from EditText. Then I want the same file to return the inputted text in String form and save it to another String which is to be used later.
Here's the code:
package com.omm.easybalancerecharge;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num = (EditText) findViewById(R.id.sNum);
Button ch = (Button) findViewById(R.id.rButton);
TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String opname = operator.getNetworkOperatorName();
TextView status = (TextView) findViewById(R.id.setStatus);
final EditText ID = (EditText) findViewById(R.id.IQID);
Button save = (Button) findViewById(R.id.sButton);
final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Get Text From EditText "ID" And Save It To Internal Memory
}
});
if (opname.contentEquals("zain SA")) {
status.setText("Your Network Is: " + opname);
} else {
status.setText("No Network");
}
ch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Read From The Saved File Here And Append It To String "myID"
String hash = Uri.encode("#");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:*141*" + /*Use The String With Data Retrieved Here*/ num.getText()
+ hash));
startActivity(intent);
}
});
}
I have included comments to help you further analyze my points as to where I want the operations to be done/variables to be used.
Hope this might be useful to you.
Write File:
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Read File:
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
For those looking for a general strategy for reading and writing a string to file:
First, get a file object
You'll need the storage path. For the internal storage, use:
File path = context.getFilesDir();
For the external storage (SD card), use:
File path = context.getExternalFilesDir(null);
Then create your file object:
File file = new File(path, "my-file-name.txt");
Write a string to the file
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write("text-to-write".getBytes());
} finally {
stream.close();
}
Or with Google Guava
String contents = Files.toString(file, StandardCharsets.UTF_8);
Read the file to a string
int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try {
in.read(bytes);
} finally {
in.close();
}
String contents = new String(bytes);
Or if you are using Google Guava
String contents = Files.toString(file,"UTF-8");
For completeness I'll mention
String contents = new Scanner(file).useDelimiter("\\A").next();
which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).
Notes
For each of these strategies, you'll be asked to catch an IOException.
The default character encoding on Android is UTF-8.
If you are using external storage, you'll need to add to your manifest either:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
or
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Write permission implies read permission, so you don't need both.
public static void writeStringAsFile(final String fileContents, String fileName) {
Context context = App.instance.getApplicationContext();
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
Logger.logError(TAG, e);
}
}
public static String readFileAsString(String fileName) {
Context context = App.instance.getApplicationContext();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
Logger.logError(TAG, e);
} catch (IOException e) {
Logger.logError(TAG, e);
}
return stringBuilder.toString();
}
Just a a bit modifications on reading string from a file method for more performance
private String readFromFile(Context context, String fileName) {
if (context == null) {
return null;
}
String ret = "";
try {
InputStream inputStream = context.openFileInput(fileName);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int size = inputStream.available();
char[] buffer = new char[size];
inputStreamReader.read(buffer);
inputStream.close();
ret = new String(buffer);
}
}catch (Exception e) {
e.printStackTrace();
}
return ret;
}
The Kotlin way by using builtin Extension function on File
Write: yourFile.writeText(textFromEditText)
Read: yourFile.readText()
check the below code.
Reading from a file in the filesystem.
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
// READ STRING OF UNKNOWN LENGTH
StringBuilder sb = new StringBuilder();
char[] inputBuffer = new char[2048];
int l;
// FILL BUFFER WITH DATA
while ((l = isr.read(inputBuffer)) != -1) {
sb.append(inputBuffer, 0, l);
}
// CONVERT BYTES TO STRING
String readString = sb.toString();
fis.close();
catch (Exception e) {
} finally {
if (fis != null) {
fis = null;
}
}
below code is to write the file in to internal filesystem.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(stringdatatobestoredinfile.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
I think this will help you.
I'm a bit of a beginner and struggled getting this to work today.
Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!
public class HighScore {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, "highscore.txt");
private int highScore = 0;
public int readHighScore() {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
highScore = Integer.parseInt(br.readLine());
br.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return highScore;
}
public void writeHighScore(int highestScore) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(highestScore));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Kotlin
class FileReadWriteService {
private var context:Context? = ContextHolder.instance.appContext
fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
val file = File(context?.filesDir, "files")
try {
if (!file.exists()) {
file.mkdir()
}
val fileToWrite = File(file, fileKey)
val writer = FileWriter(fileToWrite)
writer.append(sBody)
writer.flush()
writer.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
}
fun readFileOnInternalStorage(fileKey: String): String {
val file = File(context?.filesDir, "files")
var ret = ""
try {
if (!file.exists()) {
return ret
}
val fileToRead = File(file, fileKey)
val reader = FileReader(fileToRead)
ret = reader.readText()
reader.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
return ret
}
}
the first thing we need is the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
so in an asyncTask Kotlin class, we treat the creation of the file
import android.os.AsyncTask
import android.os.Environment
import android.util.Log
import java.io.*
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/MainFolder"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "cacheApp.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
if(result.isNotEmpty()){
//implement an interface or do something
Log.d("onPostExecuteSuccess", result)
}else{
Log.d("onPostExecuteFailure", result)
}
}
}
Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ReadandWrite {
private val mREAD = 9
private val mWRITE = 10
private var readAndWrite: Boolean = false
fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
if (Build.VERSION.SDK_INT < 23) {
readAndWrite = true
} else {
val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (mRead != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
} else {
readAndWrite = true
}
if (mWrite != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
} else {
readAndWrite = true
}
}
return readAndWrite
}
}
then in an activity, execute the call.
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this,this)
if(anRW){
pathToFileCreated = WriteFile().execute("onTaskComplete").get()
Log.d("pathToFileCreated",pathToFileCreated)
}
We can use this code to write String to a file
public static void writeTextToFile(final String filename, final String data) {
File file = new File(filename);
try {
FileOutputStream stream = new FileOutputStream(file);
stream.write(data.getBytes());
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then in the Main code, we use this, for example
writeTextToFile(getExternalFilesDir("/").getAbsolutePath() + "/output.txt", "my-example-text");
After that, check the file at Android/data/<package-name>/files.
The easiest way to append to a text file in kotlin:
val directory = File(context.filesDir, "LogsToSendToNextMunich").apply {
mkdirs()
}
val file = File(directory,"Logs.txt")
file.appendText("You new text")
If you want to just write to the file:
yourFile.writeText("You new text")
writing anything to the files, using bytes:
FileOutputStream(file).use {
it.write("Some text for example".encodeToByteArray())
}