2013년 7월 2일 화요일

(130702) 7일차 UrlTest.java (7일차 7교시 수업소스 - URL 클래스 테스트 및 문제)

 - 테스트 소스
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

public class UrlTest {

public static void main(String[] args) {
String url = "http://rss.hankyung.com/auto.xml";

// 네트워크를 통하여 웹사이트에 접속을 도와주는 클래스
try {
URL url1 = new URL(url);
// url에 접속하여 xml 문서를 읽어옴
InputStream in = url1.openStream();
// 스캐너 클래스를 이용하여 읽어드린 InputStream을 변환하여 가져옴
Scanner sc = new Scanner(in);

while(sc.hasNext())
System.out.println(sc.nextLine());

} catch (Exception e) {
e.printStackTrace();
}
}
}


 - 결과






























 - 문제 소스 (title과 description 내용만 나오도록 출력)
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.Vector;

public class UrlTest2 {

public static void main(String[] args) {
String uri ="http://rss.hankyung.com/auto.xml";
Vector<String> v = new Vector<>();

// 네트워크를 통하여 웹사이트에 접속을 도와주는 클래스
try {
URL url =new URL(uri);
// url 에 접속하여 xml문서를 읽어옴
InputStream in = url.openStream();
// 스캐너 클래스를 이용하여 읽어드린 InputStream을 변환하여 가져옴
Scanner sc =new Scanner(in);
while(sc.hasNext()){
String line = sc.nextLine().trim(); // trim()으로 공백을 제거

if(!line.equals("")){
if(line.substring(0, 3).equals("<ti")){
                                      // substring(0, 3)은 0~3에 해당하는 곳을 자른 값을 의미
v.add(line);
}else if(line.substring(0, 3).equals("<de"))
v.add(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

for (int i = 0; i <v.size(); i++) {
System.out.println(v.get(i));
}
}
}


 - 결과


























 - 문제 소스 (위 소스를 내용만 나오도록 출력)
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.Vector;

public class UrlTest4 {

public static void main(String[] args) {
String uri ="http://rss.hankyung.com/auto.xml";
Vector<String> v = new Vector<>();

//네트워크를 통하여 웹사이트에 접속을 도와주는 클래스
try {
URL url =new URL(uri);
// url 에 접속하여 xml문서를 읽어옴
InputStream in = url.openStream();
// 스캐너 클래스를 이용하요 읽어드린 InputStream을 변환하여 가져옴
Scanner sc =new Scanner(in);

while(sc.hasNext()){
String line = sc.nextLine().trim(); // trim()으로 공백을 제거

if(!line.equals("")){
if(line.substring(0, 3).equals("<ti")){ 
                                      // substring(0, 3)은 0~3에 해당하는 곳을 자른 값을 의미
String beforedata = line.substring(16, line.length()-10);      
v.add(beforedata);
}else if(line.substring(0, 3).equals("<de")){
String beforedata = line.substring(22, line.length()-15);
v.add(beforedata);
}
}
}
} catch (Exception e) {

e.printStackTrace();
}

// 0번지 1번지 2,3삭제
for (int i = 0; i <4; i++)
v.remove(0);

for (int i = 0; i <v.size(); i++) {
if(i%2==0){
System.out.print("제목 : ");
System.out.println(v.get(i));
}else{
System.out.print("기사 : ");
System.out.println(v.get(i));
}
System.out.println();
}
}
}


 - 결과