Archive | Ngôn ngữ JAVA RSS for this section

[JAVA] Thay thế “\” thành “/”

Tác giả:

  • Trần Hán Huy – tranhanhuy.wordpress.com

Đề bài

  •  Thay thế “\” thành “/” bằng java
Nguồn:

Code

public static String backlashReplace(String myStr){
    final StringBuilder result = new StringBuilder();
    final StringCharacterIterator iterator = new StringCharacterIterator(myStr);
    char character =  iterator.current();
    while (character != CharacterIterator.DONE ){

      if (character == '\\') {
         result.append("/");
      }
       else {
        result.append(character);
      }
      character = iterator.next();
    }
    return result.toString();
  }

[JAVA] Cách cài đặt và chạy trang JSP trên Localhost

Trình bày lại:

  • Trần Hán Huy – tranhanhuy.wordpress.com

Đề bài

  • Cách cài đặt và chạy trang JSP trên localhost
  • Không cần phải cài bất kì phần mềm lập trình java như netbeans, eclip hay jcreator …. vẫn có thể chạy được JSP

Phần mềm:

Nguồn: Link tham khảo bài viết: Tải đây

Ghi chú:

  • Hiện tại đã có version 6 update 3: Part 1 part 2
  • Mình sẽ viết bài hướng dẫn về version 6 update 3 (vì quá trình thao tác hơi khác với version 5 update 1)

Thiết hành setup
B1:

B2:

B3: Ở bước này theo tôi, ta nên chọn lại  đường dẫn chứa thư mục Sun. Vì khi cài đặt, tất cả ứng dụng của chúng ta điều nằm trong thư mục Sun. Vậy ta nên chọn đường dẫn đến các ổ đĩa không chứa hdh đang chạy của chúng ta. Mặt định là C, ở đây tôi đổi lại ổ đĩa D.

B4:

B5: Tại bước này, tại ô số 1 là User Name, bạn có thể thay đổi theo tên tùy thích. Tại ô 2, nhập password tối thiểu là 8 ký tự. Tại ô 3 nhập lai password giống ô 2.  Rùi nhấn Next

B6: Ở bước này bạn đánh dấu các ô vuông như hình.

B7: Tiến hành cài đặt, bạn phải chờ trong giây lát.

B8: Sau khi tiến trinh chạy xong. Bạn nhấn Finish để kết thúc quá trình cài đặt.

Đến đây chúng ta chỉ mới kết thúc quá thình cài đặt môi trường java cho các ứng dụng….Để chạy trang JSP. Bạn thực hiện các bước sau.

B1: Bạn vào Start -> Programs -> Sun Microsystems -> Application Server PE 9 -> Start Default Server.

B2: Bạn làm tương tự B1, nhưng mục cuối cùng chọn Admin Console.
Khi đó trình duyệt web xuất hiện với địa chỉ: http://localhost:4848/asadmin/admingui/TopFrameset.
Bạn nhập User NamePassword lúc khi cài đặt.
Login xong trình duyệt chúng ta sẻ mở ra trang mới.

B3: Tại cột bên trái, bạn chọn Web Applications.

B4: Tại cột bên phải, bạn chọn mục Deploy…

B5: Bạn tít vào ô Package file or a directory path that is accessible from the server. Tại ô bên đưới, bạn paste đường dẩn thư mục chứa tất cả các file của ứng dụng JSP trong máy tính của bạn.

B6: Nhấn Next.

B7: Tại ô Application Name: bạn đặt tên của ứng dụng. Ô Context Root: đây là tên của ứng dụng trên thanh địa chỉ trình duyệt.
Ví dụ: Nếu bạn đặt tên là shop thì địa chỉ la: http://localhost:8080/shop/

B8: Đặt tên xong nhấn Finish.

B9: Nhấn Launch để chạy ứng dụng.

[JAVA] Dùng DOM thao tác dữ liệu XML

Tác giả:

  • Trần Hán Huy – tranhanhuy.wordpress.com

Đề bài

  •  Dùng Dom để thao tác với XML

Chi tiết như sau

Trong đây mình hướng dẫn các bạn sử dụng DOM để thao tác với XML cụ thể với Read, Insert, Update, Delete với file XML: TuDien.XML

0. Link:

Nguồn: Link tham khảo bài viết: Tải đây

1. Cấu trúc tập tin XML như sau:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<TuDien>
   <AnhViet>
       <TiengAnh>one</TiengAnh>
       <TiengViet>một</TiengViet>
   </AnhViet>
   <AnhViet>
       <TiengAnh>Two</TiengAnh>
       <TiengViet>hai</TiengViet>
   </AnhViet>
</TuDien>

2. Read

public static ArrayList<String> ReadNode(String pFilePath,
                String pNodeName) throws Exception
{
   ArrayList<String> ds = new ArrayList<String>();
   InputSource xml = new InputSource(pFilePath);
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   DocumentBuilder db = dbf.newDocumentBuilder();
   Document doc = db.parse(xml);

   XPathFactory xpf = XPathFactory.newInstance();
   XPath xpath = xpf.newXPath();
   String exp = "//TuDien//AnhViet//" + pNodeName;

   NodeList names = (NodeList) xpath.evaluate(exp, doc,
           XPathConstants.NODESET);
   for(int i=0;i<names.getLength();i++)
   {
       Element elem = (Element)names.item(i);
       ds.add(elem.getTextContent());
   }
   return ds;
}

public static ArrayList<String> ReadTiengAnh(String pFilePath){
   try {
       return ReadNode(pFilePath, "TiengAnh");
   } catch (Exception ex) {
       Logger.getLogger(ProcessXML.class.getName())
       .log(Level.SEVERE, null, ex);
   }
   return null;
}
public static ArrayList<String> ReadTiengViet(String pFilePath){
   try {
       return ReadNode(pFilePath, "TiengViet");
   } catch (Exception ex) {
       Logger.getLogger(ProcessXML.class.getName())
       .log(Level.SEVERE, null, ex);
   }
   return null;
}
public static ArrayList<ArrayList<String>> ReadTuDienFromXML(String pFilePath)
{
   ArrayList<ArrayList<String>> mt = new ArrayList<ArrayList<String>>();
   File f = new File(pFilePath);
   if (!f.exists())//không tồn tại file XML
      return mt;
   mt.add(ReadTiengAnh(pFilePath));
   mt.add(ReadTiengViet(pFilePath))
   return mt;
}

kết quả: (mảng 2 chiều)

ReadTiengAnh: one | two
ReadTiengViet: một | hai

3. Insert

Insert dữ liệu XML có TextContent:

public static Document InsertAppendNode(String pFilePath,
     String pStrTiengAnh, String pStrTiengViet) throws Exception {
        File f = new File(pFilePath);
        Document doc = null;
        Element root = null;
        if (!f.exists()||index==0) {  //nếu như file đó không tồn tại
            doc = DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().newDocument();
            root = doc.createElement("TuDien");
            doc.appendChild(root);
        } else {
            doc = DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().parse(f);
            root = doc.getDocumentElement();
        }

        Element pAnhViet = doc.createElement("AnhViet");
        root.appendChild(pAnhViet);

        Element pTiengAnh = doc.createElement("TiengAnh");
        pTiengAnh.appendChild(doc.createTextNode(pStrTiengAnh));
        pAnhViet.appendChild(pTiengAnh);

        Element pTiengViet= doc.createElement("TiengViet");
        pTiengViet.appendChild(doc.createTextNode(pStrTiengViet));
        pAnhViet.appendChild(FileName);

        return doc;
    }

Insert dữ liệu XML có Attributes:

public static Document InsertAppendNode(String pFilePath,
        String pStrTiengAnh, String pStrTiengViet) throws Exception {
        File f = new File(pFilePath);
        Document doc = null;
        Element root = null;
        if (!f.exists()||index==0) {  //nếu như file đó không tồn tại
            doc = DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().newDocument();
            root = doc.createElement("TuDien");
            doc.appendChild(root);
        } else {
            doc = DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().parse(f);
            root = doc.getDocumentElement();
        }

        Element pAnhViet = doc.createElement("AnhViet");
        pAnhViet.setAttribute("TiengAnh",pStrTiengAnh);
        pAnhViet.setAttribute("TiengViet",pStrTiengViet);      
        root.appendChild(pAnhViet);

        return doc;
    }

4. Update

Update dữ liệu XML có TextContent:

public static void SearchAndUpdateTiengViet(Node node,
        String pStrTiengAnh, String pStrTiengViet) {
   if (node == null)
   {
       return;
   }
   if (node.getNodeName().equals("TuDien"))
   {
       NodeList list = node.getChildNodes();
       for (int index = 0; index < list.getLength(); index++)
       {
            if (list.item(index).getNodeName().equals("AnhViet"))
            {
                 if (list.item(index).getTextContent().equals(pStrTiengAnh))
                 {
                       list.item(index + 1).setTextContent(pStrTiengViet);
                       return;
                 }
            }
       }
   }
   NodeList children = node.getChildNodes();
   for (int index = 0; index < children.getLength(); index++)
   {
       SearchAndUpdateTiengViet(children.item(index),pStrTiengAnh, pStrTiengViet);
   }
}

Update dữ liệu XML có Attributes:

public static void SearchAndUpdateTiengViet(Node node,
    String pStrTiengAnh, String pStrTiengViet) {
   if (node == null)
   {
       return;
   }
   if (node.getNodeName().equals("AnhViet")) {
      if (node.getAttributes().getNamedItem("TiengAnh").
              getNodeValue().equals(pStrTiengAnh)) {
         node.getAttributes().getNamedItem("TiengViet").
              setNodeValue(pStrTiengViet);
         return;
      }
   }
   NodeList children = node.getChildNodes();
   for (int index = 0; index < children.getLength(); index++) {
      SearchAndUpdateTiengViet(children.item(index), pStrTiengAnh, pStrTiengViet);
   }
}

5. Delete

Delete dữ liệu XML có TextContent:

public static Document SearchAndDeleteTiengViet(Node node, String pStrTiengViet) {
     if (node == null) {
        return;
     }
     if (node.getNodeName().equals("TuDien")) {
        NodeList list = node.getChildNodes();
        for (int index = 0; index < list.getLength(); index++) {
           if (list.item(index).getNodeName().equals("AnhViet")) {
              if (list.item(index).getTextContent().equals(pStrTiengViet)) {
                 node.getParentNode().removeChild(node);
                 return;
              }
           }
        }
     }
     NodeList children = node.getChildNodes();
     for (int index = 0; index < children.getLength(); index++) {
        SearchAndDeleteTiengViet(children.item(index), pStrTiengViet);
     }
}

Delete dữ liệu XML có Attributes:

public static void SearchAndDeleteTiengViet(Node node, String pStrTiengViet) {
   if (node == null) {
      return;
   }
   if (node.getNodeName().equals("AnhViet")) {
      if (node.getAttributes().getNamedItem("TiengViet").
          getNodeValue().equals(pStrTiengViet)) {
         node.getParentNode().removeChild(node);
         return;
      }
   }
   NodeList children = node.getChildNodes();
   for (int index = 0; index < children.getLength(); index++) {
      SearchAndDeleteTiengViet(children.item(index), pStrTiengViet);
   }
}

6. Xuất ra file XML

Các hàm trên chỉ hoạt động trên cây DOM nằm trong bộ nhớ mà chưa thực sự được ghi xuống vào CSDL. Nếu  muốn tất cả dữ liệu đã thao tác thì sau khi gọi hàm muốn sử dụng, xong thì phải gọi thêm 1 hàm nữa, để ghi toàn bộ cây DOM ra file XML.

public static void WriteAppendXML(String pFilePath, Document Doc) throws Exception
{
    File f = new File(pFilePath);
    Source source = new DOMSource(Doc);
    Result result = new StreamResult(f);
    Transformer trans = TransformerFactory.newInstance().
        newTransformer();
    trans.transform(source, result);
}

7. Thư viện sử dụng trong project

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

[JAVA] Lấy ngày giờ hiện tại trong máy

Tác giả:

  • Trần Hán Huy – tranhanhuy.wordpress.com

Đề bài

  •  Lấy ngày giờ hiện tại trong máy bằng java

Code

import java.util.Calendar;
import java.text.SimpleDateFormat;
public class GetTimeNow {

    /**
     * @param args the command line arguments
     */
    public static String now(String dateFormat) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        return sdf.format(cal.getTime());
    }
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println(now("dd MMMMM yyyy"));
        System.out.println(now("yyyyMMdd"));
        System.out.println(now("dd.MM.yy"));
        System.out.println(now("MM/dd/yy"));
        System.out.println(now("yyyy.MM.dd G 'at' hh:mm:ss z"));
        System.out.println(now("EEE, MMM d, ''yy"));
        System.out.println(now("h:mm a"));
        System.out.println(now("H:mm:ss:SSS"));
        System.out.println(now("K:mm a,z"));
        System.out.println(now("yyyy.MMMMM.dd GGG hh:mm aaa"));
        System.out.println(now("yyyy-MM-dd hh:mm:ss" ));
    }
}

[JAVA] Lấy ngày hiện tại trong máy

Tác giả:

  • Trần Hán Huy – tranhanhuy.wordpress.com

Đề bài

  •  Lấy ngày hiện tại trong máy bằng java

Code

long current_time = System.currentTimeMillis();
java.sql.Date NgayHienTai = new java.sql.Date(current_time);