How can I load a local html file(from assets folder) to a String?
I tried this code but the result is only "?????...".
InputStream is = getAssets().open("aaa.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
System.out.println(str);
thanks for any help!
You are not reading the whole file. Try this:
StringBuilder builder = new StringBuilder();
byte[] buffer = new byte[1024];
while(is.read(buffer) != -1) {
builder.append(new String(buffer));
}
is.close();
String str = builder.toString();
try this......
File file = new File("file:///android_asset/yuor_file.html");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String linewise = br.readLine();
while(linewise != null) {
sb.append(linewise );
sb.append("\n");
linewise = br.readLine();
}
//now data in sb
Related
I am trying to compress a large string object. This is what i tried, but i am unable to understand how to get compressed data, and how to define different type of compression tools.
This is what i got from Android docs.
byte[] input = jsonArray.getBytes("UTF-8");
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
compresser.end();
compresser.deflate(output) gives me a int number, 100
but i am unable to understand which method will give me the compressed output that i can send to service.
The algorithm that I compress my data with is Huffman. You can find it by a simple search. But in your case maybe it helps you:
public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
And to decompress it you can use:
public static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}
The documentation for Deflator shows that the output gets put into the buffer output
try {
// Encode a String into bytes
String inputString = "blahblahblah";
byte[] input = inputString.getBytes("UTF-8");
// Compress the bytes
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
compresser.end();
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(output, 0, compressedDataLength);
byte[] result = new byte[100];
int resultLength = decompresser.inflate(result);
decompresser.end();
// Decode the bytes into a String
String outputString = new String(result, 0, resultLength, "UTF-8");
} catch(java.io.UnsupportedEncodingException ex) {
// handle
} catch (java.util.zip.DataFormatException ex) {
// handle
}
all code you need to ENCODE, COMPRESS , DECOMPRESS , DECODE
I'm trying to access the file path of my assets folder but for some reason, I can't access it and it creates an error(Unable to start activity ComponentInfo, Host name may not be null). What should be the correct syntax for this?
This is my code:
String xml = parser.getXmlFromUrl("file:///android_assets/music.xml");
and this is my file location:
Am I doing it properly? Or is my syntax incorrect?
try this, open an input stream on that file.
InputStreamReader is= new InputStreamReader(
context.getAssets().open("abc.xml"));
and then open and then
int length = is.available();
byte[] data = new byte[length];
is.read(data);
String xmlString = new String(data);
Hope It will help
Maybe
AssetManager assetManager = getAssets();
InputStream input = assetManager.open(fileName);
And after read file?
try using by filedescriptor as
AssetFileDescriptor descriptor = getAssets().openFd("myfile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());
Please use this code, its working code for text file as well as xml file.
public String readFromAssetsFolder(String fileName) {
String readValue = "";
InputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader input = null;
try {
fileInputStream = getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
inputStreamReader = new InputStreamReader(fileInputStream);
input = new BufferedReader(inputStreamReader);
String line = "";
while ((line = input.readLine()) != null) {
readValue = readValue+ line;
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (inputStreamReader != null)
inputStreamReader.close();
if (fileInputStream != null)
fileInputStream.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return readValue;
}
I want to read from a stream. In entity, i don't set content length and for this, i can't create a buffer with fixed and correct size. I create a buffer with 16384 length but my data is more and a parts of my data lost! I want to read from stream and write to char array and i don't want to read with readLine. How can i write this code? Please explain with a part of code.
Thanks
char[] buffer;
if (contentLength == -1)
buffer = new char[16038];
else
buffer = new char[contentLength];
InputStream stream = responseEntity.getContent();
//String resultS=convertStreamToString(stream);
InputStreamReader streamReader = new InputStreamReader(stream,"UTF-8");
int hasRead = 0;
int readSize = 0;
int bufferLength = buffer.length;
//List<Byte> listChar=new ArrayList<Byte>();
while (hasRead < bufferLength) {
readSize = streamReader.read(buffer, hasRead, bufferLength
- hasRead);
if (readSize == -1)
break;
hasRead += readSize;
}
Replace the code you posted with this:
InputStream stream = responseEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
char buffer[] = sb.toString().toCharArray();
i am trying to read the text from a file which is present on server, this file containing the text "hello world" ,now i want to write this text on TextView . i have imported all required packages . thanks in advance
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
try {
URL updateURL = new URL("http://--------------------/foldername/hello.txt");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
final String s = new String(baf.toByteArray());
((TextView)tv).setText(s);
} catch (Exception e) {
}
};
try this function ....
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);
}
is.close();
return sb.toString();
}
try this code
URL url = new URL(urlpath);
BufferedInputStream bis = new BufferedInputStream((url.openStream()));
DataInputStream dis = new DataInputStream(bis);
String full = "";
String line;
while ((line=dis.readLine())!=null) {
full +=line;
}
bis.close();
dis.close();
((TextView)tv).setText(full);
I'm porting the application from Symbian/iPhone to Android, part of which is saving some data into file. I used the FileOutputStream to save the file into private folder /data/data/package_name/files:
FileOutputStream fos = iContext.openFileOutput( IDS_LIST_FILE_NAME, Context.MODE_PRIVATE );
fos.write( data.getBytes() );
fos.close();
Now I am looking for a way how to load them. I am using the FileInputStream, but it allows me to read the file byte by byte, which is pretty inefficient:
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = iContext.openFileInput( IDS_LIST_FILE_NAME );
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
String data = new String(fileContent);
So my question is how to read the file using better way?
Using FileInputStream.read(byte[]) you can read much more efficiently.
In general you don't want to be reading arbitrary-sized files into memory.
Most parsers will take an InputStream. Perhaps you could let us know how you're using the file and we could suggest a better fit.
Here is how you use the byte buffer version of read():
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fileContent.append(new String(buffer));
}
This isn't really Android-specific but more Java oriented.
If you prefer line-oriented reading instead, you could wrap the FileInputStream in an InputStreamReader which you can then pass to a BufferedReader. The BufferedReader instance has a readLine() method you can use to read line by line.
InputStreamReader in = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(in);
String data = br.readLine()
Alternatively, if you use the Google Guava library you can use the convenience function in ByteStreams:
String data = new String(ByteStreams.toByteArray(fis));
//to write
String data = "Hello World";
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME,
Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
//to read
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
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(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
context.getFilesDir() returns File object of the directory where context.openFileOutput() did the file writing.