把Java專案壓縮為zip檔 , 寄到orange0708 at yahoo.com.tw .
會儘快回信 , 但如果很急 , 請特別告知 .
網頁
BloggerAds 廣告
標籤
- Java (96)
- Android (27)
- 演算法 (21)
- c++ (19)
- JavaScript (7)
- OpenMp (6)
- Design Pattern (4)
- 日文歌曲 (4)
- 資料結構 (4)
- Foundation Knowledge Of Programming (3)
- QUT (2)
- CodingHomeWork (1)
- Database (1)
- 英文歌詞 (1)
搜尋此網誌
2016年8月21日 星期日
2014年11月24日 星期一
Java變數命名規則
變數是區分大小寫的, 所以 int a , 和int A是兩個不同的變數.
變數不要用'$' (錢字號) 或 '_' (底線) , 作為開頭.
開頭之後可以為字母, 錢字號 , 數字 或底線.
命名要用有意義的全名, 不要用神秘的縮寫 , 讓程式碼好維護
例如 : int wheel , 比 int w, 來得好. 但是Java的關鍵字或是保留字
不可作為變數名稱.
假如變數是由兩個單字或以上所組成的 , 那麼第二個單字開始的字母必需要以大寫開頭
例如: iceCream , carWheel .
定義常數的話則是每個字母都要大寫 , 單字間要用底線連接
例如 : public static final String CAR_WHEEL = "car wheel"
下面是oracle網站列出的關鍵字和保留字, 列出供參考:
變數不要用'$' (錢字號) 或 '_' (底線) , 作為開頭.
開頭之後可以為字母, 錢字號 , 數字 或底線.
命名要用有意義的全名, 不要用神秘的縮寫 , 讓程式碼好維護
例如 : int wheel , 比 int w, 來得好. 但是Java的關鍵字或是保留字
不可作為變數名稱.
假如變數是由兩個單字或以上所組成的 , 那麼第二個單字開始的字母必需要以大寫開頭
例如: iceCream , carWheel .
定義常數的話則是每個字母都要大寫 , 單字間要用底線連接
例如 : public static final String CAR_WHEEL = "car wheel"
下面是oracle網站列出的關鍵字和保留字, 列出供參考:
abstract |
continue |
for |
new |
switch |
assert*** |
default |
goto* |
package |
synchronized |
boolean |
do |
if |
private |
this |
break |
double |
implements |
protected |
throw |
byte |
else |
import |
public |
throws |
case |
enum**** |
instanceof |
return |
transient |
catch |
extends |
int |
short |
try |
char |
final |
interface |
static |
void |
class |
finally |
long |
strictfp** |
volatile |
const* |
float |
native |
super |
while |
| * | not used | |
| ** | added in 1.2 | |
| *** | added in 1.4 | |
| **** | added in 5.0 |
2014年4月10日 星期四
常見的Java面試問題與答案1-10
Q1. 內部類別(InnerClass)和子類別(SubClass)之間的區別是什麼?
A: 內部類別是崁入在另一個類別之中的類別,並且有存取所有外部類別的方法和變數的權限
子類別是繼承自另一個類別(父類別). 並且可以存取父類別的public 和protected存取修飾子的
方法和欄位.
Q2. Java的存取修飾子有哪些?
A:
public : 類別的方法,欄位,和類別本身 , 在程式碼的任何地方皆可存取.
protected: 類別的方法和欄位, 只有在package內或是package外的子類別才可以使用.
default(無任何修飾子) : 類別的方法和欄位只有在package內部的類別使用.
private: 類別的方法和欄位只有在類別本身內才可以使用.
Q3. 靜態(static)方法和變數的目的是甚麼?
A: 當有多個物件需要共享方法和變數的時候 , 可以宣告為static . 但是要注意 , 因為宣告為static
之後 , 變數只有一份拷貝 , 因此任一此類別的物件都可更改變數值 , 如果不想要此靜態變數值
被改變, 可在前面加上final關鍵字.
Q4. 甚麼是資料封裝 , 它的重要性是甚麼?
A: 封裝可以把物件的屬性和方法隱藏在物件內部 , 只能透過物件的公開方法加以存取 , 達到
資料隱藏的目的. 良好的封裝可以增加程式碼的模組化能力, JavaBean的使用, 就是一個非常好
的例子. 物件間彼此獨立不相關 , 但是卻可透過公開介面使用彼此提供的功能.
之後 , 變數只有一份拷貝 , 因此任一此類別的物件都可更改變數值 , 如果不想要此靜態變數值
被改變, 可在前面加上final關鍵字.
Q4. 甚麼是資料封裝 , 它的重要性是甚麼?
A: 封裝可以把物件的屬性和方法隱藏在物件內部 , 只能透過物件的公開方法加以存取 , 達到
資料隱藏的目的. 良好的封裝可以增加程式碼的模組化能力, JavaBean的使用, 就是一個非常好
的例子. 物件間彼此獨立不相關 , 但是卻可透過公開介面使用彼此提供的功能.
Q5. 甚麼是獨體類別(Singleton Class) , 舉出一個實際的使用案例?
A: 獨體類別 , 顧名思義, 它只可以有一個實體, 無法創建出第二個.
常用的例子是資料庫的連線, 我們只希望透過一個實體,對資料庫連線, 不希望創建出多個實體
做資料庫連線的時候使用.
Q6. 描述Java的三種迴圈種類?
A:
1. For 迴圈 :
用在知道要重複執行多少次的時候.
2. While 迴圈 :
用在某條件預先滿足的前提下 , 持續不斷的重複執行的時候.
3. Do.While 迴圈:
和While迴圈很類似.,但是不同的地方在於, Do.While迴圈會在每次執行結束後,做條件的 判 斷
因此最少會執行一次..
Q7. 如何寫Java無限迴圈?
A:
For (;;)
Q8. continue和 break敘述式 , 不同點在哪裡?
A:
1. break :
執行迴圈若遇到break敘述 , 迴圈會立刻結束.
2. continue :
執行迴圈若遇到continue敘述 , 則continue以後的程式碼會跳過 , 直接執行下一個迴圈的判斷.
如下:
public static void main(String[]args){
for(int i = 0 ; i < 3 ; i++){
if(i == 2)
break;
if(i == 0){
continue;
}
System.out.println(i);
}
}
Q9. double和 float變數 , 在Java的不同點是?
Q10. 甚麼是final關鍵字, 請舉例?
A:
float占用4bytes的記憶體空間, double占用8bytes記憶體空間. float是單精確度十進位數字,double是倍精確度浮點數.
Q10. 甚麼是final關鍵字, 請舉例?
A:
Java利用final關鍵字來宣告常數. final宣告的變數值 , 一旦被賦予值之後 , 便不可再改變或賦值.
private final int PI = 3.14 , 是以final來宣告圓周率為常數的例子.
當方法前面加上final宣告 , 此方法便不可再被子類別所覆寫.
當類別被宣告為final , 此類別便無法繼承. 好比String, Integer , 和其他的包裹類別(Wrapped Class)
寶寶命名網
private final int PI = 3.14 , 是以final來宣告圓周率為常數的例子.
當方法前面加上final宣告 , 此方法便不可再被子類別所覆寫.
當類別被宣告為final , 此類別便無法繼承. 好比String, Integer , 和其他的包裹類別(Wrapped Class)
寶寶命名網
2013年10月13日 星期日
甚麼是類別
在物件導向程式設計 , 類別是一種藍圖 , 舉之前的車子為例, 車
子為實體, 而車子的設計圖稿就是所謂的類別. 有了設計圖稿才
能到工廠生產實際的車子.接下來實際示範車子這個類別的程
式碼 :
子為實體, 而車子的設計圖稿就是所謂的類別. 有了設計圖稿才
能到工廠生產實際的車子.接下來實際示範車子這個類別的程
式碼 :
public class Car {
/**
* 顏色欄位
*/
String color;
/**
* 設定車子顏色的方法
* @param color
*/
public void setColor(String color){
this.color = color;
}
/**
* 得到車子顏色的方法
* @return
*/
public String getColor(){
return this.color;
}
public static void main(String[] args){
Car car = new Car();//實際製造車子的實體,也就是用new這個關鍵字來創造物件.
car.setColor("blue");
System.out.println("The color of car is " + car.getColor());
}
}
甚麼是物件
物件是相關狀態和行為的結合. 而軟體物件常常被用來模擬真實世界. 好比: 車子, 狗 , 和其他的
真實物品, 都可用物件的概念來表示. 我們以車子來做例子 , 車子這個物件可以有顏色 , 大小,
和速度之類的狀態, 然後我們可以提供相關的行為來設定和改變這些狀態. 在軟體物件我們把
狀態稱為欄位(field) , 而行為我們稱之為方法(Method). 物件導向程式設計有一個很重要的觀念--
data encapsulation(資料封裝). 所謂的資料封裝 , 就是隱藏內部狀態 , 但是透過物件的方法, 來和
其他物件或是外部應用程式達到溝通的目的.
軟體物件來做程式設計有以下好處:
真實物品, 都可用物件的概念來表示. 我們以車子來做例子 , 車子這個物件可以有顏色 , 大小,
和速度之類的狀態, 然後我們可以提供相關的行為來設定和改變這些狀態. 在軟體物件我們把
狀態稱為欄位(field) , 而行為我們稱之為方法(Method). 物件導向程式設計有一個很重要的觀念--
data encapsulation(資料封裝). 所謂的資料封裝 , 就是隱藏內部狀態 , 但是透過物件的方法, 來和
其他物件或是外部應用程式達到溝通的目的.
軟體物件來做程式設計有以下好處:
- 模組化 : 可以針對不同的應用, 維護單一物件的原始碼 , 而不會影響到其他物件的原始碼或程式 . 一旦物件創造出來後 , 便可以在應用程式內部傳遞使用.
- 程式碼重用: 你可以利用別人已寫好的物件提供的功能 , 而不必自己從頭寫一個新的物件.
- 除錯容易 : 如果某個物件發生問題,或是提供的功能不完善, 你可以把這個物件抽換成別的物件, 來達到需要的功能, 而不用重新寫一份新的程式.
2013年9月9日 星期一
從無到有開發一個J2EE網頁應用程式(Web Application) -1
1. 安裝應用程式伺服器(Application Server) : Tomcat
2. 在Tomcat目錄下找到\webapps這個目錄 , 在此目錄底下建立自己的專案HelloApp
3.在HelloApp底下建立一個名為WEB-INF的目錄, 和一個HelloWorldPage.jsp 檔案
4.HelloWorldPage.jsp
5. 回到apache-tomcat-6.0.29\bin這個目錄, 執行startup.bat,啟動Tomcat 伺服器.
6. 到瀏覽器打上 http://localhost:8080/HelloApp/HelloWorldPage.jsp, 就會出現如下畫面:
- 到http://tomcat.apache.org/download-70.cgi
- 選擇 Binary Distributions底下的 Core: zip, 下載回來解壓縮.
2. 在Tomcat目錄下找到\webapps這個目錄 , 在此目錄底下建立自己的專案HelloApp
3.在HelloApp底下建立一個名為WEB-INF的目錄, 和一個HelloWorldPage.jsp 檔案
4.HelloWorldPage.jsp
5. 回到apache-tomcat-6.0.29\bin這個目錄, 執行startup.bat,啟動Tomcat 伺服器.
6. 到瀏覽器打上 http://localhost:8080/HelloApp/HelloWorldPage.jsp, 就會出現如下畫面:
2013年7月10日 星期三
2013年6月6日 星期四
Java字串比較
第一個true會成立, 是因為 equals這個api就是用來測試兩個字串是否相等, 所使用的.
第二個true會成立, 是因為 Java內部有一個字串常數池 , test2 和 test都是指到參數池裡頭同一個"test"字串 , 所以會相等.
第三個false , 是因為test3這個變數, 指到了一個新的物件, 雖然新物件的值也是"test" , 但是和物件常數池裡的"test"物件是不相同.
所以為false.
public class StringComparison {
public static void main(String[] args)
{
String test = " test ";
String test2 = " test ";
String test3 = new String("test");
System.out.println(test.equals(test2));
System.out.println(test == test2);
System.out.println(test == test3);
}
}
2013年5月21日 星期二
尋求Java程式維護專案.
我有4~5年的Java程式開發和維護的資歷 , 舉凡Spring, Hibernate , Struts , JQuery 等framework
都使用過, 維護過的程式碼有Android application , Java Web application , 只要是和Java相關的
各類型技術, 都很有信心快速上手, 解決問題 . 誠摯希望與團隊或是公司行號合作.
合作方式可以用svn , 或是說我到客戶端直接工作.
都使用過, 維護過的程式碼有Android application , Java Web application , 只要是和Java相關的
各類型技術, 都很有信心快速上手, 解決問題 . 誠摯希望與團隊或是公司行號合作.
合作方式可以用svn , 或是說我到客戶端直接工作.
2013年5月12日 星期日
A free memo application (行程安排應用程式)
我利用有空的時候寫了一個記事本app, 有興趣試玩的話可以站內留言
我可以把這個應用程式寄給你, 當然能得到意見的回饋是更好的.
This is a small application I wrote in my leisure.
Its purpose is for memorizing personal schedule.
If you are interested in this application , you can leave me a message to get its archived version.
2013年5月8日 星期三
讀取Java system properties (系統屬性)
public class SystemPropertyDemo {
public static void main(String[]args){
String fileSeparator = System.getProperty("file.separator");
String classPath = System.getProperty("java.class.path");
String javaHome = System.getProperty("java.home");
String javaVendor = System.getProperty("java.vendor");
String javaVendorUrl = System.getProperty("java.vendor.url");
String javaVersion = System.getProperty("java.version");
String lineSeparator = System.getProperty("line.separator");
String osArch = System.getProperty("os.arch");
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String pathSeparator = System.getProperty("path.separator");
String userDir = System.getProperty("user.dir");
String userHome = System.getProperty("user.home");
String userName = System.getProperty("user.name");
System.out.println(" fileSeparator: " + fileSeparator);
System.out.println(" classPath : " + classPath);
System.out.println(" javaHome : " + javaHome);
System.out.println(" javaVendor : " + javaVendor);
System.out.println(" javaVendorUrl : " + javaVendorUrl);
System.out.println(" javaVendorUrl : " + javaVersion);
System.out.println(" lineSeparator : " + lineSeparator);
System.out.println(" osArch : " + osArch);
System.out.println(" osName : " + osName);
System.out.println(" osVersion : " + osVersion);
System.out.println(" pathSeparator : " + pathSeparator);
System.out.println(" pathSeparator : " +userDir);
System.out.println(" userHome : " + userHome);
System.out.println(" userName : " + userName);
}
}
2013年5月6日 星期一
static field(靜態欄位)
static field又可稱為類別欄位 , 顧名思義所有此類別創建的物件, 會共用此欄位值 , 如下例 :
public class StaticField {
public static void main(String [] args){
Room.customer += 1;
Room room = new Room();
System.out.println(room.customer);
}
}
class Room {
static int customer = 0;
}
2013年5月5日 星期日
工廠方法創造物件(factory method creating objects)
這種寫法容易維護 , 會比單純new Student()的寫法來的好.
因為以後只要改newStudent這個method, 會同步更新到所有new Student()的地方,
而不會發生漏改的情況.
package pattern;
public class FactoryMethod {
public static void main(String [] args){
Factory.newStudent().print();
}
}
class Factory {
public static Student newStudent(){
return new Student();
}
}
class Student{
public void print(){
System.out.println("blank");
}
}
Break 和 Return的用法.
1. Break 和 Return 都可以跳離迴圈.
2. 但是Return會跳出函式而不執行接下來的程式碼.
public class BreakAndReturnDemo {
public static void main(String[] args){
printWord();
printWordWithReturn();
}
public static void printWord(){
for(int i = 0 ; i < 10 ; i++){
System.out.println(i);
if(i == 5){
break;
}
}
System.out.println("After break for loop");
System.out.println("====Seperate Line========");
}
public static void printWordWithReturn(){
for(int i = 0 ; i < 10 ; i++){
System.out.println(i);
if(i == 5){
return;
}
}
System.out.println("This line won't be executed.");
}
}
2013年4月26日 星期五
Log4j的使用方式
以下是log4j的source code拿出來做解釋
MyLoggerFactory.java: 製作MyLogger物件實體的工廠類別.
MyLogger.java: 在這裡定義每個 log level (warn, info , debug etc)想要印出的訊息.
以下這段程式碼是靜態的獨體模式(singleton design pattern)
private static MyLoggerFactory myFactory = new MyLoggerFactory();
MyLoggerTest.java:
當不傳入任何參數的時候,使用預設的log設定, 並且在console輸出 (系統標準輸出介面)
或是傳入xml, properties設定檔, 套用裡面的設定值
MyLoggerFactory.java: 製作MyLogger物件實體的工廠類別.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.subclass;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
/**
A factory that makes new {@link MyLogger} objects.
See <b><a href="doc-files/MyLoggerFactory.java">source
code</a></b> for more details.
@author Ceki Gülcü */
public class MyLoggerFactory implements LoggerFactory {
/**
The constructor should be public as it will be called by
configurators in different packages. */
public
MyLoggerFactory() {
}
public
Logger makeNewLoggerInstance(String name) {
return new MyLogger(name);
}
}
MyLogger.java: 在這裡定義每個 log level (warn, info , debug etc)想要印出的訊息.
以下這段程式碼是靜態的獨體模式(singleton design pattern)
private static MyLoggerFactory myFactory = new MyLoggerFactory();
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.subclass;
import org.apache.log4j.*;
/**
A simple example showing logger subclassing.
<p>See <b><a href="doc-files/MyLogger.java">source code</a></b>
for more details.
<p>See {@link MyLoggerTest} for a usage example.
*/
public class MyLogger extends Logger {
// It's usually a good idea to add a dot suffix to the fully
// qualified class name. This makes caller localization to work
// properly even from classes that have almost the same fully
// qualified class name as MyLogger, e.g. MyLoggerTest.
static String FQCN = MyLogger.class.getName() + ".";
// It's enough to instantiate a factory once and for all.
private static MyLoggerFactory myFactory = new MyLoggerFactory();
/**
Just calls the parent constuctor.
*/
public MyLogger(String name) {
super(name);
}
/**
Overrides the standard debug method by appending " world" at the
end of each message. */
public
void debug(Object message) {
super.log(FQCN, Level.DEBUG, message + " world.", null);
}
/**
This method overrides {@link Logger#getLogger} by supplying
its own factory type as a parameter.
*/
public
static
Logger getLogger(String name) {
return Logger.getLogger(name, myFactory);
}
public
void trace(Object message) {
//super.log(FQCN, XLevel.TRACE, message, null);
}
}
MyLoggerTest.java:
當不傳入任何參數的時候,使用預設的log設定, 並且在console輸出 (系統標準輸出介面)
或是傳入xml, properties設定檔, 套用裡面的設定值
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.subclass;
import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.LogLog;
/**
A simple example showing logger subclassing.
<p>The example should make it clear that subclasses follow the
hierarchy. You should also try running this example with a <a
href="doc-files/mycat.bad">bad</a> and <a
href="doc-files/mycat.good">good</a> configuration file samples.
<p>See <b><a
href="doc-files/MyLogger.java">source code</a></b> for more details.
*/
public class MyLoggerTest {
/**
When called wihtout arguments, this program will just print
<pre>
DEBUG [main] some.cat - Hello world.
</pre>
and exit.
<b>However, it can be called with a configuration file in XML or
properties format.
*/
static public void main(String[] args) {
if(args.length == 0) {
// Note that the appender is added to root but that the log
// request is made to an instance of MyLogger. The output still
// goes to System.out.
Logger root = Logger.getRootLogger();
Layout layout = new PatternLayout("%p [%t] %c (%F:%L) - %m%n");
root.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));
}
else if(args.length == 1) {
if(args[0].endsWith("xml")) {
DOMConfigurator.configure(args[0]);
} else {
PropertyConfigurator.configure(args[0]);
}
} else {
usage("Incorrect number of parameters.");
}
try {
MyLogger c = (MyLogger) MyLogger.getLogger("some.cat");
c.debug("Hello");
} catch(ClassCastException e) {
LogLog.error("Did you forget to set the factory in the config file?", e);
}
}
static
void usage(String errMsg) {
System.err.println(errMsg);
System.err.println("\nUsage: "+MyLogger.class.getName() + "[configFile]\n"
+ " where *configFile* is an optional configuration file, "+
"either in properties or XML format.");
System.exit(1);
}
}
2013年4月25日 星期四
用介面寫程式
用介面寫程式的好處 , 是你可以抽換運算或資料處理方式的演算法 , 而不必大幅更動程式碼
如下例 , 只要重新new 一個AnotherCustomMathAdd物件 , 把CustomMathAdd物件換掉 , 就會
得到新的結果.
如下例 , 只要重新new 一個AnotherCustomMathAdd物件 , 把CustomMathAdd物件換掉 , 就會
得到新的結果.
package convention;
public class CodingByInterface {
public static void main(String[] args){
CustomMathAdd cma = new CustomMathAdd();
add(cma , 1, 2);
}
public static void add(MathAdd ma , int a , int b){
System.out.println(ma.basicAdd(a, b));
}
}
interface MathAdd{
public int basicAdd(int a , int b);
public int advanceAdd(int a , int b);
}
class CustomMathAdd implements MathAdd {
public int basicAdd(int a, int b) {
return a + b;
}
public int advanceAdd(int a, int b) {
return a*2 + b;
}
}
class AnotherCustomMathAdd implements MathAdd {
public int basicAdd(int a, int b) {
return 0;
}
public int advanceAdd(int a, int b) {
return 1;
}
}
2013年4月24日 星期三
Rename a file
import java.io.File;
public class FileRenameDemo {
public static void main(String[] args){
File original = new File("src/dom/employee.xml");
boolean result = original.renameTo(new File("src/dom/employee.xml.backup"));
System.out.println(result);
}
}
2013年4月23日 星期二
Set usage
Set不包含兩個同樣的元素e1 and e2 , 當e1.equals(e2)為真的時候,並且Set最多只可有一個null元素.
範例:
String b = "b";
則會印出b, a
範例:
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String [] args){
String a = "a";
String b = a;
//String b = "b";
Set s = new HashSet();
s.add(a);
s.add(b);
System.out.println(s.toString());
}
}
若變數b 宣告為:String b = "b";
則會印出b, a
list to array
import java.util.LinkedList;
public class LinkedListToArray {
public static void main(String[] args){
LinkedList<String> ll = new LinkedList<String>();
ll.add("1");
ll.add("2");
ll.add("3");
String[] array = ll.toArray(new String[0]);
for(int i = 0 ; i < array.length ; i++){
System.out.println(array[i]);
}
}
}
2013年4月21日 星期日
How to read xml files in Java(Java讀取xml文件)
SAX is the Simple API for XML, originally a Java-only API
employee.xml :
W3c DOM sample :(from Java Tips):
using Dom4j: dom4j , you must have dom4j library to execute below sample code
<?xml version="1.0" encoding="UTF-8"?>
<company>
<employee>
<firstname>Michael</firstname>
<lastname>Jordan</lastname>
</employee>
<employee>
<firstname>Larry</firstname>
<lastname>Bird</lastname>
</employee>
<employee>
<firstname>Tiger</firstname>
<lastname>Woods</lastname>
</employee>
</company>
W3c DOM sample :(from Java Tips):
package dom;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class W3cDomDemo {
public static void main(String argv[]) {
try {
String path = "./bin/dom/employee.xml";
File file = new File(path);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element "
+ doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("employee");
System.out.println("Information of all employees");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt
.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : "
+ ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt
.getElementsByTagName("lastname");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Name : "
+ ((Node) lstNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
using Dom4j: dom4j , you must have dom4j library to execute below sample code
package dom;
import org.dom4j.Document;
import org.dom4j.dom.DOMDocumentFactory;
import org.dom4j.io.SAXReader;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class NativeDomDemo {
public static void main(String[] args) {
String path = "./bin/dom/employee.xml";
new NativeDomDemo().run(path);
}
public NativeDomDemo() {
}
private void run(String xmlFile) {
try {
parseDOM(xmlFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void parseDOM(String xmlFile) throws Exception {
System.out.println("Loading document: " + xmlFile);
SAXReader reader = new SAXReader(DOMDocumentFactory.getInstance());
Document document = reader.read(xmlFile);
System.out.println("Created <dom4j> document: " + document);
if (document instanceof org.w3c.dom.Document) {
org.w3c.dom.Document domDocument = (org.w3c.dom.Document) document;
System.out.println("Created W3C DOM document: " + domDocument);
processDOM(domDocument);
} else {
System.out.println("FAILED to make a native W3C DOM document!!");
}
}
protected void processDOM(org.w3c.dom.Document doc) throws Exception {
NodeList nodeLst = doc.getElementsByTagName("employee");
System.out.println("Information of all employees");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt
.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : "
+ ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt
.getElementsByTagName("lastname");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Name : "
+ ((Node) lstNm.item(0)).getNodeValue());
}
}
}
}
訂閱:
文章 (Atom)
我的網誌清單
標籤
日文歌曲
(4)
股市
(7)
股票
(9)
英文歌詞
(1)
時事
(1)
硬體(hardware)
(1)
資料結構
(4)
演算法
(21)
數學(Math)
(4)
ACM
(3)
ajax
(7)
algorithms
(1)
Android
(27)
Blog Notes(部落格記事)
(6)
C
(9)
c++
(19)
CodingHomeWork
(1)
Database
(1)
Design Pattern
(4)
Foundation Knowledge Of Programming
(3)
GWT
(1)
How
(2)
J2EE
(1)
Java
(96)
Java語言
(4)
JavaScript
(7)
Leetcode
(4)
LOL
(1)
OpenMp
(6)
QUT
(2)
Uva
(2)
Yahoo知識問答
(11)




