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
Related
I'm calling a BufferedReader to get a HTTP response body (if it exists) and stick it in one long string variable. Sometimes when I attempt to do this I get the error java.io.IOException: stream is closed sometimes when the while loop below starts to execute. I don't understand why. I'd like to make sure the object isn't null and that is has a response body before reading in the object.
BufferedReader readBuffer = null;
if (connection.getResponseCode() >= 200 && connection.getResponseCode() <= 299) {
readBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
readBuffer = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
if(readBuffer != null) {
// Get the response body output from the server
StringBuilder calculatedOutput = new StringBuilder();
String rawOutputLine;
while ((rawOutputLine = readBuffer.readLine()) != null) {
calculatedOutput.append(rawOutputLine);
}
Logger.debug(String.format("BODY: %s", calculatedOutput.toString()));
readBuffer.close();
Try this to read the response:
BufferedReader readBuffer = null;
try {
if (connection.getResponseCode() >= 200 && connection.getResponseCode() <= 299) {
readBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
readBuffer = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
// Get the response body output from the server
StringBuilder calculatedOutput = new StringBuilder();
String rawOutputLine;
while ((rawOutputLine = readBuffer.readLine()) != null) {
calculatedOutput.append(rawOutputLine);
}
Logger.debug(String.format("BODY: %s", calculatedOutput.toString()));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
readBuffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Try this code:
BufferedReader readBuffer = null;
if (connection.getResponseCode() >= 200 && connection.getResponseCode() <= 299) {
readBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
readBuffer = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
if(readBuffer != null) {
// Get the response body output from the server
StringBuilder calculatedOutput = new StringBuilder();
String rawOutputLine;
if(readBuffer.ready()) {
while ((rawOutputLine = readBuffer.readLine()) != null) {
calculatedOutput.append(rawOutputLine);
}
}
Logger.debug(String.format("BODY: %s", calculatedOutput.toString()));
readBuffer.close();
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
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 (think) I'm processing a text file line by line until I find a specific token;
(Psuedo Code)
Scanner scanner = new Scanner(new FileReader("myTextFile.txt");
while (scanner.hasNext() {
boolean found = process(scanner.nextLine();
if (found) return;
}
Some of the files are huge. Does this code actually scan the file line by line or does either the Scanner or FileReader read the entire file into memory and then work it's way through the memory buffer line by line?
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
boolean found = false;
while ((line = br.readLine()) != null) {
if(line.equalsIgnoreCase("Your string"))
found = true;
}
You want BufferedInputStream
public static void main(String[] args) {
File file = new File("C:\\testing.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
bis.close();
dis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
source
Path filePath = Paths.get("myTextFile.txt");
boolean found = false;
try (BufferedReader br = Files.newBufferedReader(filePath, CharSet.forName(<char-set-name>)){
for (String line = br.readLine(); line != null; line = br.readLine()) {
found = process(line);
if (found){
break;
};
}
}
I want to optimize this code:
InputStream is = rp.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String text = "";
String aux = "";
while ((aux = reader.readLine()) != null) {
text += aux;
}
The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above.
I need to spend as little time as possible.
Thank you
Using string concatenation in a loop is the classic performance killer (because Strings are immutable, the entire, increasingly large String is copied for each concatenation). Do this instead:
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String text = builder.toString();
You can try Apache IOUtils.toString. This is what they do:
StringWriter sw = new StringWriter();
char[] buffer = new char[1024 * 4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
sw.write(buffer, 0, n);
}
String text = sw.toString();
When BufferedReader reads from Socket, it is necessary to add bufferedReader.ready():
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb= new StringBuilder();
String line = "";
while (br.ready() && (line = br.readLine()) != null) {
sb.append(line + "\r\n");
}
String result = sb.toString();
One line solution:
String result = reader.lines().collect(joining(lineSeparator()));
Imports:
import java.io.*;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
I wrote a simple function to do this using StringBuilder and While loop with catching IOException inside.
public String getString(BufferedReader bufferedReader) {
StringBuilder stringBuilder = new StringBuilder();
String line = null;
do {
try {
if ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
} while (line != null);
return stringBuilder.toString();
}
You can use StringBuffer
while ((aux = reader.readLine()) != null) {
stringBuffer.append(aux);
}