1. 程式人生 > >Java讀取介面中的資料,並儲存到txt檔案中!

Java讀取介面中的資料,並儲存到txt檔案中!

//建立讀取介面中資料的方法
	public static String read() {
		URL url = null;
		BufferedReader reader = null;
		HttpURLConnection connection = null;
		InputStreamReader ins = null;

		try {
			// 設定url地址
			url = new URL("https://***.***.com/api/getStudent");
			System.out.println("已完成20%。。。");
			// 獲取連線通道
			connection = (HttpURLConnection) url.openConnection();
			// 設定連線響應時間
			connection.setConnectTimeout(2 * 1000);
			// 設定讀取響應時間
			connection.setReadTimeout(2 * 1000);

			// 連線
			connection.connect();
			System.out.println("已完成50%。。。");
			// 輸入流
			ins = new InputStreamReader(connection.getInputStream(), "UTF-8");
			// 讀取
			reader = new BufferedReader(ins);
			// 建立可變字串
			StringBuffer sb = new StringBuffer();
			System.out.println("已完成80%。。。");
			String line;

//			readLine()方法,當讀取流讀取資料時使用,當讀到\n、\r時,會跟著換行,
//			同時會以字串的形式返回這一行,當讀取完所有資料時,會返回null
			while ((line = reader.readLine()) != null) {
				System.out.println("匯入中。。。");
				sb.append(line + "\n");
			}
			return sb.toString();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Error GetURL:" + e);
			System.out.println("Error GetURL:" + url);
			e.printStackTrace();
		} finally {
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;

	}
//寫檔案處理
	public static void main(String[] args) {
		System.out.println("匯入開始!");
		File file = new File("F:/love.txt");
		
		if(file.exists()) {
			System.err.println("F盤下已存在love.txt的檔案,將更新檔案內容");
			file.delete();
		}
		
		if(!file.exists()) {
			try {
				file.createNewFile();
				OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file),"GB2312");
				BufferedWriter bw = new BufferedWriter(osw); 
				bw.write(read());
				System.out.println("已完成100%");
				System.out.println("匯入結束!");
				bw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}