Skip to content

Instantly share code, notes, and snippets.

@koji-k
Created July 14, 2012 16:30
Show Gist options
  • Save koji-k/3112047 to your computer and use it in GitHub Desktop.
Save koji-k/3112047 to your computer and use it in GitHub Desktop.
PHPのfile_get_contentsをJavaに移植(file_get_contents of PHP was written by Java)
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.URL;
class MyFileUtil {
/**
* PHPのfile_get_contentsもどき
* urlに指定されたページのHTMLを取得します
* @param url HTMLを取得したいページのURL
* @param encode 取得するHTMLページのURL
* @return 取得したHTML
*/
public static StringBuffer fileGetContents( String url, String encode ) {
StringBuffer buffer = new StringBuffer();
try {
InputStream is = new URL(url).openStream();
InputStreamReader isr = new InputStreamReader(is, encode);
BufferedReader in = new BufferedReader(isr);
String s = null;
while ( (s = in.readLine()) != null) {
buffer.append(s).append("\n");
}
} catch ( Exception e ) {
System.out.println( e.toString() );
buffer = null;
} finally {
return buffer;
}
}
/**
* PHPのfile_get_contentsもどき
* urlに指定されたページのHTMLを取得します
* エンコードはJISAutoDetectで自動判別させる(失敗する可能性あり!?)
* @param url HTMLを取得したいページのURL
* @return 取得したHTML
*/
public static StringBuffer fileGetContents( String url ) {
return fileGetContents( url, "JISAutoDetect" );
}
// 使い方(usage)
public static void main( String[] args ) {
StringBuffer htmlBuffer = MyFileUtil.fileGetContents( "http://example.com/" );
System.out.println( htmlBuffer.toString() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment