String Buffer is unable to convert whole data in String using toString - android

Error:
String Buffer is unable to convert whole data in String using toString
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
StringBuffer buffer =new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line +"\n");
Log.d(LOG_TAG, "line:" + line);
}
/* Close Stream */
if (null != inputStream) {
inputStream.close();
}
Log.d(LOG_TAG, "buffer.toString():" + buffer.toString());

Related

NOt able to read a InputStream

InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line ="";
while((line = bufferedReader.readLine())!= null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
message shows nothing, result is not given
The problem is that your are not appending the line into your result.
Make result variable String Buffer and use append function to do so then return the string from string buffer using toString function

How to read variable amount of json data from url?

I am using the following code to read json data from url , but it has fixed length of 500 for the json data. How can I ensure that all the data(variable length) is always read.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
Thanks.
Reference
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + newLine);
}
String result = sb.toString();
byte[] data = new byte[1024];
int bytesRead = inputstream.read(data);
while(bytesRead != -1) {
doSomethingWithData(data, bytesRead);
bytesRead = inputstream.read(data);
}

read text file returned by URL

This URL return & open text file directly, i just want to read its content how can i do it
http://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=en&tl=gu&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q=this+is+translate+demo
i have tried
public static String translate(String sl, String tl, String text) throws IOException{
// fetch
URL url = new URL("https://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=" +
sl + "&tl=" + tl + "&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q=" +
URLEncoder.encode(text, "UTF-8"));
Log.d("URL", ":: "+url);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("User-Agent", "Something Else");
Log.d("URL", ":: After opening Connection");
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
Log.d("URL", ":: br "+br);
String result = br.readLine();
br.close();
// parse
Log.d("URL", ":: "+result);
result = result.substring(2, result.indexOf("]]") + 1);
StringBuilder sb = new StringBuilder();
String[] splits = result.split("(?<!\\\\)\"");
for(int i = 1; i < splits.length; i += 8)
sb.append(splits[i]);
return sb.toString().replace("\\n", "\n").replaceAll("\\\\(.)", "$1");
}
If Your Url directly open's the Text File then this code reads the TextFile and print's also as follows:
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

Read a simple text file

Hi everyone I am trying to read the date from a file in android. I am using Eclipse and the program is compiling and running, just it is not printing the context of the txt file. Here is my load method
private String load(String filename) {
try {
// Log.v("Home", " in the load method");
Log.d("Home", " in the load method");
final FileInputStream fis = openFileInput(filename);
// final InputStream fis = getResources().openRawResource(R.raw.pages);
final BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
fis.close();
return sb.toString();
} catch (Exception ex) {
return "No entry exists for this file";
}
}
and in the oncreate i just access it
String fileName = "pages.txt";
load(fileName);
pages.txt is in the res/raw directory. I tried to read the file with both
final FileInputStream fis = openFileInput(filename);
// final InputStream fis = getResources().openRawResource(R.raw.pages);
but It is not printing the context.
I added in the onCreate method
Log.d("File", load(fileName));
but is returning the catch statement No entry exists for this file.
Thanks
try to use like below,
System.out.println(load(raw.pages));
private String load(int id) {
try {
Resources res = getResources();
InputStream fis = res.openRawResource(id);
final BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
fis.close();
return sb.toString();
} catch (Exception ex) {
return "No entry exists for this file";
}
}

Read file As String

I need to load an xml file as String in android so I can load it to TBXML xml parser library and parse it. The implementation I have now to read the file as String takes around 2seconds even for a very small xml file of some KBs. Is there any known fast method that can read a file as string in Java/Android?
This is the code I have now:
public static String readFileAsString(String filePath) {
String result = "";
File file = new File(filePath);
if ( file.exists() ) {
//byte[] buffer = new byte[(int) new File(filePath).length()];
FileInputStream fis = null;
try {
//f = new BufferedInputStream(new FileInputStream(filePath));
//f.read(buffer);
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}
//result = new String(buffer);
}
return result;
}
The code finally used is the following from:
http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
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();
}
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;
}
You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs) to do that.
e.g.
IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)
For adding the correct library:
Add the following to your app/build.gradle file:
dependencies {
compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
}
https://stackoverflow.com/a/33820307/1815624
or for the Maven repo see -> this link
For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi
Reworked the method set originating from -> the accepted answer
#JaredRummler An answer to your comment:
Read file As String
Won't this add an extra new line at the end of the string?
To prevent having a newline added at the end you can use a Boolean value set during the first loop as you will in the code example Boolean firstLine
public static String convertStreamToString(InputStream is) throws IOException {
// http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
Boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if(firstLine){
sb.append(line);
firstLine = false;
} else {
sb.append("\n").append(line);
}
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws IOException {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
It's very easy if you use Kotlin:
val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)
From readText() docs:
Gets the entire content of this file as a String using UTF-8 or
specified charset. This method is not recommended on huge files. It
has an internal limitation of 2 GB file size.
With files we know the size in advance, so just read it all at once!
String result;
File file = ...;
long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
result = "";
Log.w(TAG, "File is empty or huge: " + file);
} else {
try (FileReader in = new FileReader(file)) {
char[] content = new char[(int)length];
int numRead = in.read(content);
if (numRead != length) {
Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
}
result = new String(content, 0, numRead);
}
catch (Exception ex) {
Log.e(TAG, "Failure reading " + this.file, ex);
result = "";
}
}
public static String readFileToString(String filePath) {
InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
try {
return IOUtils.toString(in, StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("Failed to read the xml : ", e);
}
return null;
}
this is working for me
i use this path
String FILENAME_PATH = "/mnt/sdcard/Download/Version";
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;
}

Categories

Resources