How to download xml data of a website? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have searched about this. All I got was xml parsing/ Sax parser. I need a program that will download xml data.
I need this for my android application development. thanks
For example i have a website localhost:8080/folder/sample.html.. How do i get a .xml file from that?

Sorry if I'm not answering the question - but is it the website content, you want to download? If positive, these are similar questions where the solution may lie:
How to get a web page's source code from Java
Get source of website in java
How do I retrieve a URL from a web site using Java?
How do you Programmatically Download a Webpage in Java
A good library to do URL Query String manipulation in Java

try this code:
public String getXmlText(String urlXml) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
String result = null;
try {
url = new URL(urlXml);
is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
result = result + line + "\n";
}
} catch (Exception e) {
return "";
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {}
}
return result;
}

Try this code
import java.net.*;
import java.io.*;
class Crawle {
public static void main(String ar[]) throws Exception {
URL url = new URL("http://www.foo.com/your_xml_file.xml");
InputStream io = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(io));
FileOutputStream fio = new FileOutputStream("file.xml");
PrintWriter pr = new PrintWriter(fio, true);
String data = "";
while ((data = br.readLine()) != null) {
pr.println(data);
}
}
}

Related

why doesn't my file delete no matter why I do? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public void removeLine(String s) throws IOException, FileNotFoundException{
File tempFile = new File("temp.txt");
FileInputStream reader = new FileInputStream(sharkFile);
Scanner scanner = new Scanner(reader);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile, true));
String currentLine;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
trimmedLine.equals(sharkName);
if(trimmedLine.equals(sharkName)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
scanner.close();
scanner = null;
reader.close();
writer.flush();
writer.close();
writer = null;
System.gc();
if(!sharkFile.delete()){
System.out.println("Could not delete file d");
return;
}
if(!tempFile.renameTo(sharkFile)){
System.out.println("Could not rename file");
return;
}
}
I've gone through numerous threads on stackoverflow and have implemented those changes but my file just won't delete. Appreciate the help.
The File API is notoriously weak on explaining why something fail, e.g. File.delete() simply returns a boolean, and value false cannot explain why.
Use the new Path API instead.
Also, please (PLEASE!) use try-with-resources.
Scanner is slow, so better to use BufferedReader, and for writing the lines back with newlines, use a PrintWriter.
Path sharkPath = sharkFile.toPath();
Path tempPath = Paths.get("temp.txt");
Charset cs = Charset.defaultCharset();
try (BufferedReader reader = Files.newBufferedReader(sharkPath, cs);
PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tempPath, cs, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)))) {
for (String currentLine; (currentLine = reader.readLine()) != null; ) {
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
if (! trimmedLine.equals(sharkName))
writer.println(currentLine);
}
}
Files.delete(sharkPath); // throws descriptive exception if cannot delete
Files.move(tempPath, sharkPath); // throws exception if cannot move
Use below code, rename file before delete, it's appearing that you are accessing file name after delete:
try { //rename file first
tempFile.renameTo(sharkFile);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Unable to rename.");
}
try {
sharkFile.delete();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "Unable to delete.");
}

How to add a tumblr feed into a java swing project [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm making a launcher for my game using Java Swing. I need a way to add a tumblr/wordpress feed onto the launcher. An example would be the minecraft launcher (If you don't know what it looks like, go to this link).
I was also thinking RSS could be useful because I've seen that mentioned on feeds and stuff like this so if there's a simple way with that then that'd be helpful too.
Anyway, how would I do this?
EDIT: How would I use jsoup in Swing?
Here's an example I have used to parse data from a page
private static final String url = "website";
public void getLatestUpdate() throws IOException {
try {
URL addr = new URL(url);
URLConnection con = addr.openConnection();
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Pattern p = Pattern.compile("<span itemprop=.*?</span>");
Pattern p2 = Pattern.compile(">.*?<");
Matcher m = p.matcher(inputLine);
Matcher m2;
while (m.find()) {
m2 = p2.matcher(m.group());
while (m2.find()) {
data.add(m2.group().replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("#", "").replaceAll(";", "").replaceAll("3", "3"));
}
}
}
in.close();
addr = null;
con = null;
message("(" + data.get(3) + ")" + ", at " + data.get(4));
} catch (Exception e) {
System.out.println("Error getting data from website.");
e.printStackTrace();
}
}

Java, automatic reading file from a directory [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to know if it's possible to do this:
i've some .txt file in a directory in my filesystem
i would like to write a java code that does this:
Automatically read all the files in the directory
Give me a output
Exists some library? or it's just a code problem?
It's possible?
Thanks
Reads & prints the content
public static void main(String[] args) {
List<String> li=new TestClass().textFiles("your Directory");
for(String s:li){
try(BufferedReader br = new BufferedReader(new FileReader(s))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} catch (IOException e) {
e.printStackTrace();
}
}
}
For getting all Text files in the Directory
List<String> textFiles(String directory) {
List<String> textFiles = new ArrayList<String>();
File dir = new File(directory);
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.add(file.getPath());
}
}
return textFiles;
}
Of course it's possible. You need to look at File, Reader classes. A useful method is File#listFiles. Happy coding.

How to get the page source from specific link in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Is it possible to get the inputStream of particular website content or it's page source into String?
For instance, I want to download the whole html tag from particular website into string or xml. Is it possible?
Yes of course you just have to do something like
public static void main(String[] args) {
URL url;
try {
// get URL content
url = new URL("http://www.mkyong.com");
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
//save to this filename
String fileName = "/users/mkyong/test.html";
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
//use FileWriter to write file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((inputLine = br.readLine()) != null) {
bw.write(inputLine);
}
bw.close();
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
CREDIT : mkyong
You may want to look at guava's CharStreams class.
CharStreams.toString(new InputStreamReader(..))
will save you from writing much boilerplate code.
Here is doc

How can i find the City name using IP address in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want city name from IP address using Java
is there any idea to do this ?
From Andrey link, here is how to construct the inquiry, this code will return an HTML file with all details of current IP, including city;
String IP= "123.123.123.123";
URL link = new URL("http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="+IP);
BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
in.close();
UPDATE, 23 May 2013
The previous answer is ok, but it's not an API call, it reads an HTML page, that I provided previously because I didn't find any free APIs. Next is a REST API call that can be used easily and will return all the info required, it's recommended to use this one:
String ip = "2.51.255.200";
URL url = new URL("http://freegeoip.net/csv/" + ip);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
int status = connection.getResponseCode();
if (status != 200) {
return null;
}
reader = new BufferedReader(new InputStreamReader(is));
for (String line; (line = reader.readLine()) != null;) {
//this API call will return something like:
"2.51.255.200","AE","United Arab Emirates","03","Dubai","Dubai","","x-coord","y-coord","",""
// you can extract whatever you want from it
}
If your Application is deployed behind the firewall. So instead of calling a API, we can use GeoLite below is the sample code.
Download City.dat file from http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
File datapath = new File("GeoLiteCity.dat");
LookupService cl = new LookupService(datapath,
LookupService.GEOIP_MEMORY_CACHE
| LookupService.GEOIP_CHECK_CACHE);
String cityName = cl.getLocation(ipAddress).city;

Categories

Resources