I am writing Android. The app should read line of a file from web, and shows the message on the textView. I use bufferedReader. It works fine when I have bufferedReader.readLine() inside a while loop. But it does not work when I have it in a IF statement (shows nothing, although there's something I see in debug mode).
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://www.tc.umn.edu/~yang4131/jtest.json");
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==HttpURLConnection.HTTP_OK){ // 200
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
/*
if((line = bufferedReader.readLine()) != null)
result += line;
if((line = bufferedReader.readLine()) != null)
result += line;
if((line = bufferedReader.readLine()) != null)
result += line;
*/
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result; // this return statement is needed, no matter what
}
I replicated this thing in pure Java in Eclipse, with a local file. It works fine. I really have no idea.
Solved.
Adding result += "\n\n\n\n"; after the concatenation will make the content appear. I think this has something to do with UI, perhaps my textView is blocked for few lines or whatnot.
Related
Below is the code:
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The following is my output:
Context successfully set
Script started
LXKADMIN|In/OutBoundValidation|-|50149.11065.26960.11788|inbound=OFF|outbound=OFF
inbound=OFF|outbound=OFF
Script complete
STEP 1: COMPLETED
PASSED: step1
I want to fetch the line 5 "inbound=OFF|outbound=OFF" and check if its value is matching "inbound=OFF|outbound=OFF" then my test case will pass else it will fail.
The TCL Script is:
tcl;
eval {
puts "Script started"
set schemaValidationStr [mql temp query bus LXKADMIN In/OutBoundValidation * select id description dump '|']
puts $schemaValidationStr
set schemaValidation [string range $schemaValidationStr 57 end]
puts $schemaValidation
puts "Script complete"
}
Any suggestion will be really helpful.
If your question is just how to verify that the output returned by your TCL script, contains a specific line, than you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String EXPECTED_LINE_VALUE = "inbound=OFF|outbound=OFF";
public boolean verifyScriptOutput(ChannelExec channel)
throws IOException
{
// Check all lines in output
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
String line;
int linenr = 0;
while ((line = reader.readLine()) != null)
{
linenr++;
if (linenr == CHECK_LINE_NR)
return (line.equals(EXPECTED_LINE_VALUE));
}
// If we get here, output has less lines
return (false);
} // verifyScriptOutput
The point at which you are reasoning is not possible because you can not access the console and see what is visualized. Instead you should process the input that the console gets, and outputs it, which is the line variable in your case.
If for you is enough to see that inbound=OFF|outbound=OFF you can search that substring in the line like this:
if(line.indexOf("inbound=OFF|outbound=OFF") != -1) {
// you have a match
}
I'm not sure I understood the question, but you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String CHECK_LINE_VALUE = "inbound=OFF|outbound=OFF";
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int linenr;
boolean line_check_passed;
linenr = 0;
line_check_passed = false;
while ((line = reader.readLine()) != null) {
linenr++;
if (linenr == CHECK_LINE_NR)
line_check_passed = line.equals(CHECK_LINE_VALUE);
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public static boolean check(InputStream in, int line, String expected) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int i = 0;
String str;
while ((str = reader.readLine()) != null) {
if (i < line)
i++;
else
return expected.equals(str);
}
return false;
}
Need help from you regarding a Scenario, i.e., I have to take a value from DB like "42258258.2300" and convert this into "42,258,258.00" value.
And again need to check whether this value present in downloaded CSV file.
I used below code for read from CSV file but am not getting the output. Kindly help me on this.
String strFile = "outputfile.csv";
FileInputStream fstream = new FileInputStream(strFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String ss = "$42,699,561.00";
if(strLine.contains(ss)){
System.out.println ("Success"); }
}
in.close();
What do you get if you print strLine? Are you really getting the string?
This code works for me
public void getFileInformation(){
String strFile = "/Users/myUser/Documents/outputfile.csv";
BufferedReader br = null;
String strLine = "";
String ss = "$42,699,561.00";
try {
br = new BufferedReader(new FileReader(strFile));
while ((strLine= br.readLine()) != null) {
if(strLine.contains(ss)){
System.out.println ("Success");
}else{
System.out.println (strLine);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But the content "$42,699,561.00"; should really exist in the file
I trying to read a json file from dbpedia and parse it. But the code that i have wrote can not correctly read the whole json file and for that reason parsing error comes. Here is my code for reading and parsing...
URL url=new URL("http://dbpedia.org/data3/assembly.json");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine="asdf";
while (( in.readLine()) != null)
{
if (inputLine=="asdf")
inputLine=in.readLine();
else
inputLine+=in.readLine();
//System.out.println(inputLine);
}
System.out.println(inputLine);
Object obj = parser.parse(inputLine);
JSONObject jsonObject = (JSONObject) obj;
You can create a helper method to read the file from url:
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
then you can call the method like this
try {
JSONObject json = new JSONObject(readUrl("http://dbpedia.org/data3/assembly.json"));
...
} catch (JSONException e) {
e.printStackTrace();
}
It's up to you, if you need StringBuffer or StringBuilder
so i am new to java.please offer some sample codes if possible.
The situation is i have a html format in a text file. i need to read the file and find the string after a pattern which is 'data-name'. i need to find every string after the "data-name" through the entire text file. i did some research online . i already used html parser to get the html and store it in a text file. i know i might need to use regular expression. so please help me. Thank you guys!
below is my code for getting the html. the result is concatenated.
public static void main(String[] args) {
try {
URL url = new URL("https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
PrintWriter out = new PrintWriter(new FileWriter("C:/Users/Desktop/htmlsourcecode.txt"));
while ((line = in.readLine()) != null) {
System.out.println(line);
out.print(line);
}
out.close();
}
How about something like this
// External resource(s).
BufferedReader in = null;
PrintWriter out = null;
try {
URL url = new URL(
"https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
in = new BufferedReader(new InputStreamReader(
url.openStream()));
String line;
// out = new PrintWriter(new FileWriter(
// "htmlsourcecode.txt"));
final String DATA_NAME = "data-name=\"";
while ((line = in.readLine()) != null) {
int pos1 = line.indexOf(DATA_NAME); // opening position.
if (pos1 > -1) { // did we match?
// Add the length of the string.
pos1 += DATA_NAME.length();
// find the closing quote.
int pos2 = line.indexOf("\"", pos1 + 1);
if (pos2 > -1) {
String dataName = line.substring(pos1,
pos2);
System.out.println(dataName);
// out.print(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close external resource(s).
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
out.close();
}
}
i am using this code.
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((br.readLine()) != null) {
temp1 = br.readLine();
temp2 = br.readLine();
}
in.close();
}catch (Exception e){//Catch exception if any
Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), temp1+temp2, Toast.LENGTH_LONG).show();
but this is showing exception and is not updating temp1 and temp2.
The exception you see - that I would strongly recommend a) to catch as a specific type, e.g. IOException, and b) to log or show with a message or a stack trace, and c) at least to check for in LogCat, from the DDMS perspective if you are programming with Eclipse - is probably due to Android not finding the config.txt file you are trying to open. Usually, for the simplest cases such as yours, files that are private to an application are opened using openFileInput - see the documentation for details.
Apart from the exception, your reading loop is defective: you need to initialize an empty string before entering, and fill it in the while condition.
String line = "";
while ((line = br.readLine()) != null) {
// do something with the line you just read, e.g.
temp1 = line;
temp2 = line;
}
However, you don't need a loop if you just want to save the first two lines in different variables.
String line = "";
if ((line = br.readLine()) != null)
temp1 = line;
if ((line = br.readLine()) != null)
temp2 = line;
As others have already pointed out, calling readLine consumes a line, so if your config.txt file contains only one line your code consumes it on the while condition, then temp1 and temp2 get null assigned because there's no more text to read.
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
temp1 = line;
temp2 = line;
}
in.close();
}catch (Exception e){//Catch exception if any
Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), temp1+temp2, Toast.LENGTH_LONG).show();
br.readLine() in while already consumes a line.
Try this
LineNumberReader reader = new LineNumberReader(new FileReader("config.txt")));
String line;
while ((line = reader.readLine()) != null) {
//doProcessLine
}
if you want to save the first two lines you have to do:
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
if((line = br.readLine()) != null)
temp1 = line;
if((line = br.readLine()) != null)
temp2 = line;
}
catch(Exception e)
{
e.printStackTrace();
}