Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, August 1, 2019

Java: 將function print 轉移到變量

// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Print some output: goes to your special stream
System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);
// Show what happened
System.out.println("Here: " + baos.toString());

Reference: https://stackoverflow.com/questions/8708342/redirect-console-output-to-string-in-java

Tuesday, June 12, 2018

Java: ascii和unicode變換

在爬網頁時遇到\u6C39\u4ED4這種unicode字符,希望把它們還原回來,於是找到了java有個包叫︰native2ascii是字符轉unicode,和unicode轉字符ascii2native。

經過搜一下native2ascii就會找到連結下載︰如這裏
用法是在加入bulid path之後,使用Native2Ascii.nativeToAscii(str);就可以了。
ascii2native的代碼可以參考這裏

Monday, May 14, 2018

Java: sendGet request時亂碼問題

InputStreamReader沒有加入UTF-8,導致發在tomcat server中錯誤分析回傳的內容的編碼。


======================= URLConnection.java ======================
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.json.JSONObject;

public class URLConnection {
private final String USER_AGENT = "Mozilla/5.0";

// HTTP GET request
public JSONObject sendGet(String input_url, HashMap<String, String> parameter_map) throws Exception {
String parameter_string = "";
Iterator<Entry<String, String>> it = parameter_map.entrySet().iterator();
while (it.hasNext()){
Entry<String, String> pair = it.next();
parameter_string += "?" + URLEncoder.encode(pair.getKey(), "UTF-8") + "=" + URLEncoder.encode(pair.getValue(), "UTF-8");
}

String url = input_url + parameter_string;

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET
con.setRequestMethod("GET");

//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

//print result
JSONObject responseJson = new JSONObject(response.toString());
return responseJson;
}
}

Wednesday, October 25, 2017

Java: SQL 整理

在Java對DB進行操作的其中幾項重點︰
PreparedStatement pstmt = null; // 可以對語句自動進行預處理, 跳脫符號等。

pstmt = conn.prepareStatement("update XXX set name = ? where id = ?");
pstmt.clearParameters();
pstmt.setString(1, name); // 第一個問號自動填入這個字串
pstmt.setString(2, id); // 第二個問號自動填入這個字串
pstmt.executeUpdate(); // 執行更新
pstmt.close();

其中,當需要得到從DB中的結果時,需要使用ResultSet。
ResultSet rs = null;
......
rs = pstmt.executeQuery(); // 運行query並回傳結果到rs
while(rs.next()) {
ip = rs.getString(1); // 得到第一個column
}


Sunday, July 17, 2016

Java: QR Code生成

最近在一個網頁上生成了幾個 QR Code,在登記的時候沒有發現他只有十五日的試用期。當然,現在的試用期已經過了,所以那些 QR Code 就沒法再用了。

唔...這件事情讓我打算做一個自己的QR Code生成器吧。所以就找到下面這個例子,應該滿好懂的,總之就下用Maven下載版本是3.2.1的zxing-core︰

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.2.1</version>
</dependency>

然後把代碼貼上去就可以了,這個代碼可以直接用,所以都沒有什麼可以說的。XD

Reference: Java: Simple QR Code Generator Example – Now you Could have Narrow Border

Sunday, January 3, 2016

Error: java連接phpmyadmin時, 出現Access denied for user XXX

錯誤描述︰
java.sql.SQLException: Access denied for user 'XXX'@'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)

出現地點︰Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);

解決方法︰在頁面中新增用戶的時候要用IP指定host,例如localhost的IP是127.0.0.1。有可能是因為本機不知道localhost是在哪裡。在頁面中選擇Add User後,填寫host的時候要用IP地址。