ApacheFileUtils Library
- http://commons.apache.org/proper/commons-io/
- http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html
- Most developers put jars in the project’s \lib folder
- Add to Build path: Access Denied
- Clear Hidden Attribute
- Set Everyone for ‘Full Control’
Code:
package com.lynda.files;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadNetworkFile {
public static void main(String[] args) {
try {
URL url = new URL("http://services.explorecalifornia.org/rss/tours.php");
InputStream stream = url.openStream();
BufferedInputStream buf = new BufferedInputStream(stream);
StringBuilder sb = new StringBuilder();
while (true) {
//buff.read will return number of character read
//will send -1 if end of file/stream
int data = buf.read();
if (data == -1) {
break;
}
else {
//convert data to char
sb.append((char)data); //Type Casting
}
}
System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ParseXML
- get jdom or use java base classes:
Code:
package com.lynda.files;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ReadXML {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("http://services.explorecalifornia.org/rss/tours.php");
NodeList list = doc.getElementsByTagName("title");
System.out.println("There are " + list.getLength() + " items");
for (int i = 0; i < list.getLength(); i++) {
Element item = (Element)list.item(i);
System.out.println(item.getFirstChild().getNodeValue());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Log in to post comments