이 튜토리얼에서는 java에서 URL의 내용을 읽는 방법을 보여줍니다. 이 메소드는 read라는 메소드를 작성합니다.이 메소드는 입력에서 String을 취해 URL의 컨텐츠를 리턴합니다. 자습서 코드를 실행하고 파일을 다운로드하려면 다음 단계를 수행해야합니다.
import java.io.IOException; import java.io.InputStream; import java.net.URL; public class ReadUrlContent { public String read(String url) throws IOException { // URL에서 스트림 열기 InputStream is = new URL(url).openStream(); StringBuilder sb = new StringBuilder(); int cp; while ((cp = is.read()) != -1) { sb.append((char) cp); } // Object를 문자열로 반환 return sb.toString(); } public static void main(String[] argv) { ReadUrlContent example = new ReadUrlContent(); // URL 내용을 읽으십시오. String googleContent = ""; try { googleContent = example.read("http://oliviertech.com/"); } catch (Exception e) { e.printStackTrace(); } int pos = googleContent.indexOf( "oliviertech" ); // 출력물에 내용을 표시하십시오. System.out.println(googleContent.substring(pos, pos+20)); } }
oliviertech.com" typ
oliviertech의 최초의 인스턴스의 뒤의 String로 돌려 주어지는 텍스트