This question already has answers here:
Loading html file to webview on android from assets folder using Android Studio
(3 answers)
Closed 5 years ago.
try {
File f = new File( "file:///android_asset/[2011]011TAXMANN.COM00167(PATNA)") ;
FileInputStream fis= new FileInputStream(f);
System.out.println("_______YOUR HTML CONTENT CODE IS BELLOW WILL BE PRINTED IN 2 SECOND _______");
Thread.sleep(2000);
int ch;
while((ch=fis.read())!=-1)
{
fileContent=fileContent+(char)ch; // here i stored the content of .Html file in fileContent variable
}
System.out.print(fileContent);
//}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is my code. I want to read html content from asstes folder my file is available in asstes folder But it gives exception FileNotFoundException. So plz any one tell me how to read html content from asstes folder in android?
File f = new File( "file:///android_asset/[2011]011TAXMANN.COM00167(PATNA)") ;
when i debug f gives= file:/android_asset/[2011]011TAXMANN.COM00167(PATNA)
plz tell me how to get corrct directory and where i m doing wrong it shud me coming file:///android_asset/[2011]011TAXMANN.COM00167(PATNA)
This is the way to load HTML file from assets in WebView
webview.loadUrl("file:///android_asset/Untitled-1.html");
Untitled-1.html---File name that should be save first as .html extension
Edited
try this link
http://developer.android.com/reference/android/content/res/AssetManager.html
there is method from this doc
public final String[] list (String path)
You cat get InputStream by this code:
getResources().getAssets().open("you_file_name_goes_here");
you don't want to use
webview.loadUrl('file:///android_asset/htmlFile.html');
right?
try this i found it in a blog:
static String getHTMLDataBuffer(String url,Context context) {
InputStream htmlStream;
try {
if (Utils.isReferExternalMemory() && url.contains("sdcard")) {
String tempPath = url.substring(7, url.length());//remove file:// from the url
File file = new File(tempPath);
htmlStream = new FileInputStream(file);
}else{
String tempPath = url.replace("file:///android_asset/", "");
htmlStream = context.getAssets().open(tempPath);
}
Reader is = null;
try {
is = new BufferedReader(new InputStreamReader(htmlStream, "UTF8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// read string from reader
final char[] buffer = new char[1024];
StringBuilder out = new StringBuilder();
int read;
do {
read = is.read(buffer, 0, buffer.length);
if (read>0) {
out.append(buffer, 0, read);
}
} while (read>=0);
return out.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
usage:
String data = getHTMLDataBuffer("file:///android_asset/yourHtmlFile",this);
webview.loadDataWithBaseURL("http://example.com", data, "text/html", "utf-8", null);
Sorry for my bad english :)
Related
I want to know how can I use java to confirm a file is a picture file.
I have tried the following code:
public static void main(String[] args) {
// get image format in a file
File file = new File("C:/Users/dell、/Desktop/4.xlsx");
// create an image input stream from the specified fileDD
ImageInputStream iis = null;
try {
iis = ImageIO.createImageInputStream(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get all currently registered readers that recognize the image format
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
System.out.println("Not a picture file");
throw new RuntimeException("No readers found! Unable to read the uploaded file");
}
// get the first reader
ImageReader reader = iter.next();
try {
System.out.println("Format: " + reader.getFormatName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close stream
if (iis != null){
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
But it doesn't work perfectly! It shows an exception once the file is not a picture file, so I want to find a better way.
There are too many image extensions. Maybe the best way to validate if a file is an image, is using Regular Expressions. Something like this...
([^\s]+(\.(?i)(jpg|png|gif|bmp|MORE|IMAGE|EXTENSIONS))$)
Here is a complete example of the implementation.
Use ImageIO#read.
public static boolean isPictureFile(File file){
try{
return ImageIO.read(file) != null;
}catch(Exception ex){
return false;
}
}
Basically, the method ImageIO.read(File) will return a BufferedImage object when it successfully read the image file, a null otherwise. All we have to do is to let ImageIO read the file and check if it returns a null or not, and if there it throws an exception for whatever reason, we can safely assume the file is not a picture file.
I am trying to convert large 3gp file(>than 25mb) to byte array but it gives outofmemory exception.i am able to convert less than 25 mb 3gp file to bytearray.
File file1 = new File (Environment.getExternalStorageDirectory() + "1.3gp");
FileInputStream fis = null;
try {
fis = new FileInputStream(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while (fis.available() > 0) {
bos.write(fis.read());
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] bytes = bos.toByteArray();
File someFile = new File (Environment.getExternalStorageDirectory()+ "/output.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(someFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
////
how to convert the large 3gp file into bytearray.
give a proper example or method.
Set the -Xmx option on the virtual machine being used to run the program to a larger value to give it more memory to work with.
You can do that as a command line option if running the program directly, or as a setting on the project in your IDE if running it from an IDE.
I download audio files from server using
try {
// URL url = new URL("http://commonsware.com/misc/test2.3gp");
URL url = new URL("http://192.168.0.2/supplications/"+fileName);
//URL url = new URL("http://www.msoftech.com/supplications/android/"+fileName);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.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) {
Log.d("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: " +cd2);
Here PATH = "/data/data/packagename/sounds/filename
It works fine, audio file downloaded and played successfully, but my problem is when I click the home button and then restart the app means the folder with the downloaded audio was not found, ie, when exit the app means all the downloaded audios were deleted automatically. It throws the exception file not found.
For playing the downloaded file I used the code as below,
public void audioPlayer(String path, String fileName) throw FileNotFoundException
{
//set up MediaPlayer
FileInputStream fileInputStream = new FileInputStream(PATH+"/"+fileName);
//String command = "chmod 666 " + recordFile.toString();
try {
mp.setDataSource(fileInputStream.getFD());
// mp.setDataSource(path+"/"+filename.mp3);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
whats the problem with it what I have to do for saving the audio file permenantly.
There is nothing problem in your code it is a file permission issue.
When you download file into internal file system under application package a security is assigned to it like "-rw------" this means your file is accessible for the same application only.As android is on Linux based so every file have some permission.
Your file would be there but not accessible to other application like media player etc, so these application throws error like file not found.(you can check though DDMS tool).
Just change the file path to external drive.
Accept the answer if it is helpful.
I'm trying to save a url as a string so that I can use it in another part of my app but its not working properly. Here's what I have.
Saving
String FILENAME = "usertimetable";
String string = mWebView.getOriginalUrl();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Opening
FileInputStream fis = null;
try {
fis = openFileInput("usertimetable");
url = fis.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try using the read() method, rather than toString().
(http://developer.android.com/reference/java/io/FileInputStream.html for more info.)
I asked a question earlier about extracting RAR archives in Java and someone pointed me to JUnrar. The official site is down but it seems to be quite widely used as I found a lot of discussions about it online.
Could someone show me how to use JUnrar to extract all the files in an archive? I found a little snippet online but it doesn't seem to work. It shows each item in the archive to be a directory even if it is a file.
Archive rar = new Archive(new File("C://Weather_Icons.rar"));
FileHeader fh = rar.nextFileHeader();
while(fh != null){
if (fh.isDirectory()) {
logger.severe("directory: " + fh.getFileNameString() );
}
//File out = new File(fh.getFileNameString());
//FileOutputStream os = new FileOutputStream(out);
//rar.extractFile(fh, os);
//os.close();
fh=rar.nextFileHeader();
}
Thanks.
May be you should also check this snippet code. A copy of which can be found below.
public class MVTest {
/**
* #param args
*/
public static void main(String[] args) {
String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
File f = new File(filename);
Archive a = null;
try {
a = new Archive(new FileVolumeManager(f));
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File("/home/rogiel/fs/test/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}