Skip to content

Instantly share code, notes, and snippets.

@Benjamin1021523
Last active August 13, 2019 06:12
Show Gist options
  • Save Benjamin1021523/1701eb96206b779e1595ce0cc3f82466 to your computer and use it in GitHub Desktop.
Save Benjamin1021523/1701eb96206b779e1595ce0cc3f82466 to your computer and use it in GitHub Desktop.
java練習
import java.io.*;
import java.net.*;
public class ConnectWeb{
public static void main(String[] args){
http();
https();
}
static void https(){//https目前還是不行,試過網路上的code失敗
String target = "https://gist.githubusercontent.com/Benjamin1021523/1701eb96206b779e1595ce0cc3f82466/raw/fc71033195bdec93457f39fe26cbef74701dcce2/Example.java";
}
static void http(){
String target = "http://127.0.0.1:5000/show/";
try{
URL url = new URL(target);
InputStream stream = url.openStream();
String content = readAll(stream, "UTF-8");
System.out.print(content);
}
catch(Exception e){
System.out.println(e);
}
}
static String readAll( InputStream stream, String charcode ) throws IOException{
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream, charcode)
);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
return sb.toString();
}
}
import java.util.*;
public class Example{
public static void main(String[] args){
List<Integer> a = new ArrayList<Integer>();
for(int i = 0;i < 5;i++) a.add(i);
List<Integer> b = a;
for(int i:a) System.out.print(i + " ");
System.out.println();
for(int i:b) System.out.print(i + " ");
System.out.println();
}
}
//b初始化時使用了和a同樣的一塊記憶體
//就像linux指令的ln -h一樣
//印出1~10000間的質數
public class PrimeNumber{
public static void main(String[] args){
int n = 9974;//No prime number in 9974 ~ 10000
boolean[] arr = new boolean[n];
for(int i = 2;i < n;i++){
if(!arr[i]){
for(int j = i+i;j < n;j += i){
arr[j] = true;
}
}
}
int cnt = 0;
for(int i = 2;i < n;i++){
if(!arr[i]){
System.out.printf(i + " ");
++cnt;
if(cnt % 10 == 0) System.out.println();
}
}
System.out.println();
}
}
//單純的讀檔印出,使用個物件還要自己在以外的地方加throws真是麻煩
import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException{
String name = "Example.java";
String charset = "utf8";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(name),
charset
)
);
String Line;
while((Line = reader.readLine()) != null){
System.out.println(Line);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment