Unable to merge two mp3 files - java

public class MainActivity extends Activity {
FileInputStream fistream2,fistream1;
File newFile=new File(Environment.getExternalStorageDirectory()
+File.separator
+"newfolder" //folder name
+File.separator
+"media"
+File.separator
+"player"+File.separator+"theonkar10.mp3");
File newFile1=new File(Environment.getExternalStorageDirectory()
+File.separator
+"newfolder" //folder name
+File.separator
+"media"
+File.separator
+"player"+File.separator+"1.mp3");
File newFile2=new File(Environment.getExternalStorageDirectory()
+File.separator
+"newfolder" //folder name
+File.separator
+"media"
+File.separator
+"player"+File.separator+"2.mp3");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
myMethod();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void myMethod() throws IOException
{
FileInputStream fistream1 = new FileInputStream(newFile1.getAbsolutePath()); // first source file
FileInputStream fistream2= new FileInputStream(newFile2.getAbsolutePath());//second source file
//SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
// FileOutputStream fostream = new FileOutputStream("C:\\Temp\\final.mp3");//destinationfile
FileOutputStream fostream=new FileOutputStream(newFile.getAbsolutePath(),true);
if(!newFile.exists()){
newFile.mkdirs();
int temp;
while( ( temp = sistream.read() ) != -1)
{
System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
}
I am getting a new file theonkar10.mp3 but the file is of 0 bytes.Probably I am missing a simple step.

three things to get this thing working ^^
create the FILE not the directory!
newFile.createNewFile();
then another important part is: create the fileoutputstream AFTER you created the file!
and third, it seems the sequenceinputstream works not properly for me, when i use the two-arguemnt-constructor, instead use the constructor with the enumerator.
here's the summary ^^
public void myMethod() throws IOException
{
FileInputStream fistream1 = new FileInputStream(newFile1 ); // first source file
FileInputStream fistream2= new FileInputStream(newFile2 );//second source file
Vector<FileInputStream> v = new Vector<FileInputStream>();
v.add(fistream1);
v.add(fistream2);
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
if(!newFile.exists()){
newFile.createNewFile();
FileOutputStream fostream=new FileOutputStream(newFile, true);
int temp;
while( ( temp = sistream.read() ) != -1)
{
System.out.print( (char) temp ); // to print at DOS prompt
fostream.write((byte)temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
it's working here with my env...

Related

Saving and reading txt file when app closed and opened

Now I have app which save and read some text into .txt file by button. How can I make that app save file after app closed and reading file when app opened automatically, without any click on buttons?
public class mAcitivity extends AppCompatActivity {
private Button btn_read, btn_save;
private TextView textView;
private String txt = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
btn_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readFile();
textView.setText(txt);
}
});
}
public String readFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
try {
FileInputStream fis = new FileInputStream(file);
int size = fis.available();
byte[] buffer = new byte[size];
fis.read(buffer);
fis.close();
txt = new String(buffer);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mActivity.this, "Error reading file", Toast.LENGTH_LONG).show();
}
return txt;
}
public void saveFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
if (file.exists()){ file.delete();}
try {
String sometxt = "Hello world";
FileOutputStream out = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(out);
pw.println(sometxt);
pw.flush();
pw.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can use your MainActivity lifecycle callbacks to begin your I/O operations directly, or start BoundService which will operate them.
You can achieve this by putting your saveFile() method inside stop() lifecycle method, and putting your readFile() method inside start() lifecycle method. Activity will automatically call start() method once the application starts and it will call stop() method once the applicqtion closes/terminates.

Problems understanding context and contextwrapper

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.

"Invalid File" error when the images in sdcard are clicked

To share the image via Email and mms first step I need to save the image in sdcard but for me the saved image is not getting opened instead "Invalid File" error, I checked with the extension format everything is correct but don't know where I'm going wrong.
Below is the java code.
public class Share extends CordovaPlugin {
public static final String ACTION_POSITION = "ShareImage";
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (ACTION_POSITION.equals(action)) {
try {
JSONObject arg_object = args.getJSONObject(0);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("image/jpg");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, arg_object.getString("image"));
String name = arg_object.getString("image");
String defType = "drawable";
String defPackage = "com.picsswipe";
int drawableId = this.cordova.getActivity().getResources().getIdentifier( name , defType, defPackage );
// Bitmap bbicon = BitmapFactory.decodeFile( arg_object.getString("image") );
Bitmap bbicon = BitmapFactory.decodeResource( this.cordova.getActivity().getResources(),drawableId );
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File f = new File(extStorageDirectory + "/Download/",
"jj.jpg" );
try {
outStream = new FileOutputStream(f);
bbicon.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
}
File r1 = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Download/", "jj.jpg");
//RETRIEVING IMAGES FROM SDCARD
Uri uri1 = Uri.fromFile(r1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri1);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(r1));
Uri uris = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "jj.jpg"));
this.cordova.getActivity().startActivity(sendIntent);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
return true;
}
}
File file;
File rootPath = android.os.Environment
.getExternalStorageDirectory();
File directory = new File(rootPath.getAbsolutePath()
+ "/Download");
if (!directory.exists())
directory.mkdir();
file = new File(directory, "filename.PNG");//.png/.jpg anything you want
try {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pincheck);
FileOutputStream outStream;
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and you should add this permission in your manifest file..Then only file will copied to your external sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Join MP3 files - converting Java code to Android

I am trying to make a program which can join 2 MP3 files and save them on the android SD card. I have Java code that is working but when I try to convert it to Android it gives some error.
In Java code is written below. It's working perfect.
import java.io.*;
public class TuneDoorJava {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fistream1 = new FileInputStream("F:\\aa.mp3"); // first source file
FileInputStream fistream2 = new FileInputStream("F:\\bb.mp3");//second source file
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
FileOutputStream fostream = new FileOutputStream("F:\\final.mp3");//destinationfile
int temp;
while( ( temp = sistream.read() ) != -1)
{
// System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
In Android, what I'm trying to do is:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FileOutputStream fostream=null;
FileInputStream fist=(FileInputStream)getResources().openRawResource(R.raw.t);
FileInputStream fist2=(FileInputStream)getResources().openRawResource(R.raw.v);
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1");
dir.mkdirs();
File file = new File(dir, "filename");
//FileInputStream fistream1 = new FileInputStream(); // first source file
//FileInputStream fistream2 = new FileInputStream("F:\\bb.mp3");//second source file
SequenceInputStream sistream = new SequenceInputStream(fist, fist2);
FileOutputStream fostream = new FileOutputStream(file);
int temp;
while( ( temp = sistream.read() ) != -1)
{
// System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
- Give this permission WRITE_EXTERNAL_STORAGE
Here is the working code from my project:
public class ConcateSongActivity extends Activity {
Button mbutt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mbutt = (Button)findViewById(R.id.button_Click_Karo);
mbutt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
FileInputStream fis1 = new FileInputStream("/sdcard/viv0.wav");
FileInputStream fis2 = new FileInputStream("/sdcard/viv1.wav");
SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
FileOutputStream fos = new FileOutputStream(new File("/sdcard/vis.wav"));
int temp;
try {
while ((temp = sis.read())!= -1){
fos.write(temp);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
You need to give your app the permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android: Epub file not showing images in emulator/android device

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);

Categories