Read Url to String in Few Lines of Java Code

Reading first 5 lines of a URL, then printing in reverse order

Take Reading Directly from a URL as a initial example, since it is already an elegant piece of code and accomodate it to your needs. For example ...

import java.net.*;
import java.io.*;
import java.util.*;

public class DataURL {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

int i=5; /* number lines */
List<String> lines = new ArrayList<String>();
while (i>0 && (inputLine = in.readLine()) != null) {
lines.add(inputLine);
i--;
}
in.close();

for (i=lines.size()-1; i >= 0; i--) {
System.out.println("Line " + i + ": " + lines.get(i));
}
}
}

This code simply reads the first five lines and then outputs them in reverse order.

how to get url html contents to string in java

Resolved it using spring
added the bean to the spring config file

  <bean id = "receiptTemplate" class="org.springframework.core.io.ClassPathResource">
<constructor-arg value="/WEB-INF/Receipt/Receipt.html"></constructor-arg>
</bean>

then read it in my method

        // read the file into a resource
ClassPathResource fileResource =
(ClassPathResource)context.getApplicationContext().getBean("receiptTemplate");
BufferedReader br = new BufferedReader(new FileReader(fileResource.getFile()));
String line;
StringBuffer sb =
new StringBuffer();

// read contents line by line and store in the string
while ((line =
br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();

Read String line by line

You can also use the split method of String:

String[] lines = myString.split(System.getProperty("line.separator"));

This gives you all lines in a handy array.

I don't know about the performance of split. It uses regular expressions.

posting url with string parameter that contains LINE BREAKS using java

If it's a URL you can use the percent-encoded value for a new line, it's %0D%0A although %0A (ASCII 10 - line feed) or %0D (ASCII 13 - carriage return) should work alone.

Is there a FileReader equivalent for a URL in Java?

It's URLConnection.

Here's an example from Java documentation : Reading from and Writing to a URLConnection :

import java.net.*;
import java.io.*;

public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}


Related Topics



Leave a reply



Submit