How to read from .txt file - android

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

Related

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

Correct file path of assets android

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

Load local HTML file(from assets) to a String

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

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";
}
}

Categories

Resources