宿題スレPart56 606 (HPのソースをtxtに)


宿題スレPart56 >>606 (HPのソースをtxtに)

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
/**
* Source Getter
*/
public class SourceGetter {
	public static void main(String[] args) {
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		try {
			// HPにHTTPコネクションを張る
			connection = (HttpURLConnection) new URL("http", "www.hp.com",
					"/index.html").openConnection(); // index.htmlをよこせ
			connection.setRequestMethod("GET"); // GETメソッド
			// 読込用Readerを取得
			reader = new BufferedReader(new InputStreamReader(connection
					.getInputStream()));
			// 1行づつStringBuilderに取り込んで、最後まで読込
			String line = null;
			StringBuilder builder = new StringBuilder();
			while ((line = reader.readLine()) != null) {
				builder.append(line).append("\n");
			}
			// txtファイルに書き出す
			PrintWriter writer = null;
			try {
				writer = new PrintWriter(new File("source.txt"));
				writer.write(builder.toString());
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (writer != null) {
					writer.close();
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) { // nop
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
	}
}

CONTENTS

最新の20件

2020-11-14 2005-12-06 2006-11-04 2012-07-15 2009-06-19 2011-03-03 2006-12-13 2007-11-05 2014-07-22 2014-07-19 2014-07-09 2014-01-14 2012-09-03 2012-03-28

今日の20件

人気の30件

  • counter: 4375
  • today: 1
  • yesterday: 0
  • online: 1