File

import java.io.File;


public class FileDemo {

public static void main(String[] args) {

System.out.println("File.separator = " + File.separator);

System.out.println("file.separator = " + System.getProperty("file.separator"));

System.out.println("File.pathSeparator = " + File.pathSeparator);

System.out.println("path.separator = " + System.getProperty("path.separator"));

}

}

출력:

File.separator = /

file.separator = /

File.pathSeparator = :

path.separator = :

//윈도우즈는 파일구분이 \로, 리눅스는 /, 그리고 경로구분은 윈도우즈는 ; , 리눅스는 :

----------------------------------------------

import java.io.File;

import java.io.IOException;

import java.util.Scanner;


public class FileDemo1 {

public static void main(String[] args) {

FileDemo1 fd = new FileDemo1();

File file = new File(fd.getPath());

System.out.println("Path = " + file.getPath());

System.out.println("Absolute path = " + file.getAbsolutePath());

try{  //CanonicalPath는 익셉션을 던짐

System.out.println("Canonical path = " + file.getCanonicalPath());

}catch(IOException ex){}

}

String getPath(){

System.out.print("파일 경로 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

파일 경로 : src/FileDemo1.java

Path = src/FileDemo1.java

Absolute path = /home/mino/JavaRoom/0401/src/FileDemo1.java

Canonical path = /home/mino/JavaRoom/0401/src/FileDemo1.java

출력:

파일 경로 : ../0401/src/FileDemo1.java

Path = ../0401/src/FileDemo1.java

Absolute path = /home/mino/JavaRoom/0401/../0401/src/FileDemo1.java

Canonical path = /home/mino/JavaRoom/0401/src/FileDemo1.java

//getPath는 내가 입력한 경로. 진짜 절대경로는 CanonicalPath. AbsolutePath를 쓰는것이 일반적이지만 cannicalPath는 익셉션처리를 해주어야함.

//AbsolutePath를 두번째처럼 쓰는 경우는 거의 없기 때문에 일반적으로 AbsolutePath를 써도 괜찮다.

--------------------------------------------

import java.io.File;

import java.util.Date;

import java.util.Scanner;


public class FileDemo2 {

public static void main(String[] args) {

File file = new File(new FileDemo2().getPath());

if(file.exists()){

System.out.println("Name : " + file.getName());

System.out.println("Absolute : " + file.getAbsolutePath());

System.out.println("Permission : " + file.canRead());

System.out.println("Permission : " + file.canWrite());

System.out.println("Permission : " + file.canExecute());

System.out.println("file or directory : " + file.isDirectory());

System.out.println("Created Date : " + file.lastModified());

System.out.println("Created Date : " + new Date(file.lastModified()));

System.out.println("Size : " + file.length());

}else{

System.out.println("파일 혹은 디렉토리를 찾을 수 없습니다");

}

}

String getPath(){

System.out.print("파일 및 디렉토리 경로 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

파일 및 디렉토리 경로 : src/FileDemo2.java

Name : FileDemo2.java

Absolute : /home/mino/JavaRoom/0401/src/FileDemo2.java

Permission : true

Permission : true

Permission : false

file or directory : false

Created Date : 1396315823000

Created Date : Tue Apr 01 10:30:23 KST 2014

Size : 994

출력:

파일 및 디렉토리 경로 : /home/mino/JavaRoom

Name : JavaRoom

Absolute : /home/mino/JavaRoom

Permission : true

Permission : true

Permission : true

file or directory : true

Created Date : 1396313223000

Created Date : Tue Apr 01 09:47:03 KST 2014

Size : 4096

-----------------------------------------------------------

파일 이름변경

import java.io.File;

import java.util.Scanner;


public class FileDemo3 {

public static void main(String[] args) {

FileDemo3 fd = new FileDemo3();

File file = new File(fd.getPath());

if(file.exists()){

String newName = fd.getPath();

System.out.println(file.renameTo(new File(newName)));

}else System.out.println("Not Found");

}

String getPath(){

System.out.print("파일명 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

파일명 : /home/mino/sungjuk_utf8.dat

파일명 : /home/mino/sungjuk.dat

true

//처음에 이름을 변경할 파일을 입력하고, 두번째는 이름을 어떻게 바꿀건지 한다. 성공하면 true

-------------------------------------------------------

파일 삭제

import java.io.File;

import java.util.Scanner;


public class FileDemo3 {

public static void main(String[] args) {

FileDemo3 fd = new FileDemo3();

File file = new File(fd.getPath());

if(file.exists()){

System.out.println(file.delete());

}else System.out.println("Not Found");

}

String getPath(){

System.out.print("파일명 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

파일명 : /home/mino/sungjuk.dat

true

//파일이 삭제된다.

------------------------------------------------------------

목록

import java.io.File;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Scanner;


public class FileDemo4 {

public static void main(String[] args) {

File file = new File(new FileDemo4().getPath());

if(file.exists()){

if(file.isDirectory()){

File [] array = file.listFiles();  //디렉토리의 모든 파일을 파일 배열에 넣어줌.

for(File f : array){

System.out.print(f.getName() +"  \t\t");

String pattern = "MM월 dd   HH:mm";

SimpleDateFormat sdf = new SimpleDateFormat(pattern);

System.out.print(sdf.format(new Date(f.lastModified())) +"\t\t");

if(f.isDirectory()) System.out.println("<DIR>");

else System.out.println(f.length() + " Bytes");

}

}else System.out.println("디렉토리가 아닙니다.");

}else System.out.println("Not Found");

}

String getPath(){

System.out.print("디렉토리 경로 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

디렉토리 경로 : src

FileDemo3.java   04월 01   10:40 508 Bytes

FileDemo1.java   04월 01   10:03 606 Bytes

FileDemo.java   04월 01   09:59 384 Bytes

FileDemo4.java   04월 01   10:54 970 Bytes

FileDemo2.java   04월 01   10:30 994 Bytes

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.Font;


import javax.swing.JFrame;

import javax.swing.JTree;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.DefaultTreeModel;


public class JTreeDemo {

private JFrame f;

private Container con;

private JTree tree;

private Font font;

private JTreeDemo(){

this.f = new JFrame("JTree Demo");

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.font = new Font("Monospaced", Font.PLAIN, 15);

this.con = this.f.getContentPane();

this.tree = new JTree();

}

private void display(){

this.con.setLayout(new BorderLayout());

this.tree.setFont(this.font);

this.tree.setModel(getModel());

this.con.add("Center", this.tree);

this.f.setSize(300, 800);

this.f.setLocationRelativeTo(null);

this.f.setVisible(true);

}

private DefaultTreeModel getModel(){

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java-Oracle");

DefaultMutableTreeNode os = new DefaultMutableTreeNode("OS");

DefaultMutableTreeNode windows = new DefaultMutableTreeNode("Windows8.1");

DefaultMutableTreeNode ubuntu = new DefaultMutableTreeNode("Ubuntu");

DefaultMutableTreeNode centos = new DefaultMutableTreeNode("CentOS");

os.add(windows);  os.add(ubuntu);  os.add(centos);

DefaultMutableTreeNode language = new DefaultMutableTreeNode("language");

DefaultMutableTreeNode c = new DefaultMutableTreeNode("C-language");

DefaultMutableTreeNode java = new DefaultMutableTreeNode("Java");

language.add(c);   language.add(java);

DefaultMutableTreeNode db = new DefaultMutableTreeNode("DB");

DefaultMutableTreeNode derby = new DefaultMutableTreeNode("Derby");

DefaultMutableTreeNode sqlite = new DefaultMutableTreeNode("Sqlite");

DefaultMutableTreeNode mysql = new DefaultMutableTreeNode("MySQL");

DefaultMutableTreeNode oracle = new DefaultMutableTreeNode("Oracle");

db.add(derby);  db.add(sqlite);  db.add(mysql);    db.add(oracle);

DefaultMutableTreeNode web = new DefaultMutableTreeNode("Web");

DefaultMutableTreeNode html5 = new DefaultMutableTreeNode("HTML5");

DefaultMutableTreeNode css3 = new DefaultMutableTreeNode("CSS3");

DefaultMutableTreeNode javascript = new DefaultMutableTreeNode("JavaScript");

DefaultMutableTreeNode ajax = new DefaultMutableTreeNode("Ajax");

DefaultMutableTreeNode xml = new DefaultMutableTreeNode("XML");

DefaultMutableTreeNode jquery = new DefaultMutableTreeNode("jQuery");

web.add(html5);  web.add(css3);   web.add(javascript);   web.add(ajax);

web.add(xml);   web.add(jquery);

DefaultMutableTreeNode framework = new DefaultMutableTreeNode("Framework");

DefaultMutableTreeNode struts = new DefaultMutableTreeNode("Struts");

DefaultMutableTreeNode spring = new DefaultMutableTreeNode("Spring");

framework.add(struts);  framework.add(spring);

DefaultMutableTreeNode project = new DefaultMutableTreeNode("Project");

DefaultMutableTreeNode first = new DefaultMutableTreeNode("1차 프로젝트");

DefaultMutableTreeNode second = new DefaultMutableTreeNode("2차 프로젝트");

DefaultMutableTreeNode third = new DefaultMutableTreeNode("3차 프로젝트");

project.add(first);  project.add(second);   project.add(third);

root.add(os);   root.add(language);   root.add(db);  root.add(web);

root.add(framework);   root.add(project);

DefaultTreeModel dtm = new DefaultTreeModel(root);

return dtm;

}

public static void main(String[] args) {

new JTreeDemo().display();

}

}

//출력은 "Java-Oracle"가 루트폴더, 그리고 아래 파일들이 정렬. 다같이 만들어줫으나 파일을 붙여주면 그것은 폴더처럼됨. 

펼치면 담겨있는 것을 볼 수 잇음.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

탐색기

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.Dimension;

import java.awt.Toolkit;


import javax.swing.JFrame;

import javax.swing.JSplitPane;

import javax.swing.JTable;

import javax.swing.JTextArea;

import javax.swing.UIManager;


public class Explorer {

private JFrame f;

private JSplitPane pane;

private Container con;

private LeftPane  left;

private JTable table;

private JTextArea ta;

private RightPane  right;

private Explorer(){

this.f = new JFrame("File Manager");

this.con = this.f.getContentPane();

this.pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);

this.right = new RightPane();

this.left = new LeftPane(this.right);

}

private void display(){

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.pane.setLeftComponent(this.left);

this.pane.setRightComponent(this.right);

this.con.setLayout(new BorderLayout());

this.con.add("Center", this.pane);

this.f.setLocationRelativeTo(null);

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

this.f.setSize((int)dim.getWidth(), (int)dim.getHeight());

this.f.setVisible(true);

}

public static void main(String[] args) {

//API에서 javax.swing.plaf.~~ 써져있는 것을 볼 수 있다.

//Metal : javax.swing.plaf.metal.MetalLookAndFeel

//GTK : com.su.java.swing.plat.gtk.GTKLookAndFeel    -안먹힘

//Nimbus : com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel

//Motif : com.sun.java.swing.plaf.motif.MotifLookAndFeel

//Windows : com.sun.java.swing.plaf.windows.WindowsLookAndFeel   -안먹힘

try{

UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

}catch(Exception ex){}

new Explorer().display();

}

}







import java.awt.CardLayout;


import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.JTextArea;


public class RightPane extends JPanel {

private JScrollPane scrollTable, scrollTextArea;

private JTable table;

private JTextArea ta;

private CardLayout card;

RightPane(){

this.card = new CardLayout();

this.setLayout(card);

this.table = new JTable();

this.scrollTable = new JScrollPane(this.table);    //디렉토리를 선택했을 때

this.ta = new JTextArea();

this.scrollTextArea = new JScrollPane(this.ta);   //파일을 선택했을 때

this.add(this.scrollTable, "table");

this.add(this.scrollTextArea, "area");

card.show(this, "table");

this.setSize(480, 700);

}

JTable getTable(){ return this.table; }

void setTable(JTable table){ this.table = table; }

JTextArea getTextArea() { return this.ta; }

void setTextArea(JTextArea ta) { this.ta = ta; }

CardLayout getCardLayout(){  return this.card; }

}








import java.awt.BorderLayout;

import java.awt.Dimension;

import java.io.File;


import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTree;

import javax.swing.tree.DefaultMutableTreeNode;


LeftPane(RightPane right){

//Linux, Unix

this.right = right;

this.root = new DefaultMutableTreeNode("내 컴퓨터");

//루트 디렉토리(드라이브명)을 출력

File [] array = File.listRoots();  //모든 루트 디렉토리를 돌려준다.

for(File f : array){

if(f.isDirectory()){  //디렉토리라면

DefaultMutableTreeNode node = new DefaultMutableTreeNode(f.getPath());

node.add(new DefaultMutableTreeNode("EMPTY"));  //각폴더에 모두 empty를 넣음. 모두 폴더화. 확장은 이벤트에 의해 해주기 위해.

this.root.add(node);

}

}

//특정 루트 디렉토리의 디렉토리만을 출력(특정 드라이브)

/*File file = new File("c:/");  

File [] array = file.listFiles();  //루트밑에있는 폴더들을 모두 파일 배열에 넣음.

for(File f : array){

if(f.isDirectory()){  //디렉토리라면

DefaultMutableTreeNode node = new DefaultMutableTreeNode(f.getName());

node.add(new DefaultMutableTreeNode("EMPTY"));  //각폴더에 모두 empty를 넣음. 모두 폴더화. 확장은 이벤트에 의해 해주기 위해.

this.root.add(node);

}

}*/

//루트디렉토리 출력을 toString을 사용하는 방법

/* File [] array = File.listRoots();    // 변경 : Root부터 디렉토리(C:\, D:\, ...)를 찾음

   for(int i = 0; i< array.length; i++){

       if(array[i].isDirectory()){  // 변경 

          DefaultMutableTreeNode node = new DefaultMutableTreeNode(array[i].toString().trim()); // 변경 : Root밑에 디렉토리(C:\, D:\, ...)를 연결함

          node.add(new DefaultMutableTreeNode("EMPTY"));

          this.root.add(node);

       }


   }*/


this.tree = new JTree(this.root);

this.tree.addTreeWillExpandListener(new TreeAction());  //트리확장할 것이다.

this.tree.addTreeSelectionListener(new TreeSelection(this, this.right));

this.scroll = new JScrollPane(this.tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

                                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

this.setLayout(new BorderLayout());

this.add("Center", this.scroll);

this.setPreferredSize(new Dimension(200,  700));

}

}







import java.io.File;

import java.util.Enumeration;

import java.util.StringTokenizer;


import javax.swing.event.TreeExpansionEvent;

import javax.swing.event.TreeWillExpandListener;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.ExpandVetoException;

import javax.swing.tree.MutableTreeNode;

import javax.swing.tree.TreeNode;

import javax.swing.tree.TreePath;


public class TreeAction implements TreeWillExpandListener {


@Override

public void treeWillExpand(TreeExpansionEvent event)

throws ExpandVetoException {

TreePath path = event.getPath();

//System.out.println(path);    출력 -> [/, home]

StringTokenizer st = new StringTokenizer(path.toString(), "[,]");

st.nextToken();   //   /를 날려주고 뒤에 폴더이름만 가져오게 하기 위해

//System.out.println(st.nextToken());  출력 -> usr, home ~~~~

if(st.hasMoreTokens()){  //다음토큰이 있는 경우에 오류발생 방지.

String node = File.separator + st.nextToken().trim();    //     /home

//System.out.println(node);  //출력-> /tmp, /home, ~~

while(st.hasMoreTokens()){  //[1,home,계정]이니 다음이 없을 때까지

node += File.separator + st.nextToken().trim();

}

File file = new File(node); /////            /home

//System.out.println(file.getAbsolutePath());  //절대경로를 출력

File [] array = file.listFiles();

if(array == null) return;  //자식이 없으면 그냥 넘기고

DefaultMutableTreeNode temp =    //home

 (DefaultMutableTreeNode)event.getPath().getLastPathComponent();

temp.removeAllChildren();  //붙이기전에 다지움. 이걸 하지 않으면 자기자신을 택하면 또 자기자신이 나오는 현상 발생

for(File f : array){

if(f.isDirectory()){

DefaultMutableTreeNode tn = new DefaultMutableTreeNode(f.getName());

tn.add(new DefaultMutableTreeNode("EMPTY"));  //마지막 폴더를 선택했을 때 비어있다면 empty표시

temp.add(tn);

}else if(f.isFile()){

temp.add(new DefaultMutableTreeNode(f.getName()));

}

}

}

}


@Override

public void treeWillCollapse(TreeExpansionEvent event)

throws ExpandVetoException {}

}






import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Vector;


import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.event.TreeSelectionEvent;

import javax.swing.event.TreeSelectionListener;

import javax.swing.table.DefaultTableModel;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.TreeNode;

import javax.swing.tree.TreePath;


public class TreeSelection implements TreeSelectionListener {

private JPanel panel;

private RightPane right;

TreeSelection(JPanel panel, RightPane right){

this.panel = panel;

this.right = right;

}

@Override

public void valueChanged(TreeSelectionEvent e) {

TreePath path = e.getPath();

//System.out.println(path);    //[/, home]

DefaultMutableTreeNode node = 

(DefaultMutableTreeNode)e.getPath().getLastPathComponent();  //경로상의 제일 마지막 

//System.out.println(node);  // home, sys 처럼 앞의 경로는 두고 마지막 경로상의 값만 출력한다.

TreeNode [] array = node.getPath();

String str = "";

for(int i = 1 ; i < array.length ; i++){  //1부터 쓴 이유는 출력이 usr을 찎으면 ///usr로 시작한다. 처음에 /로 시작하고 separator붙여주고 해서 제일처음 부분을 제거한 것이다.

str += File.separator + array[i];

}

File file = new File(str);

if(file.isDirectory()){  //디렉토리를 선택했다면

File [] fileArray = file.listFiles();

Vector<String> columnVector = new Vector<String>(1,1);

columnVector.addElement("Name");

columnVector.addElement("Modifeied Date");

columnVector.addElement("Directory");

columnVector.addElement("size");

Vector<Object> dataVector = new Vector<Object>(1,1);

for(File f : fileArray){

Vector<String> imsi = new Vector<String>(1,1);

imsi.addElement(f.getName());

long date = f.lastModified();

String pattern = "YYYY-MM-dd HH:mm:ss";

SimpleDateFormat sdf = new SimpleDateFormat(pattern);

imsi.addElement(sdf.format(new Date(date)));

if(f.isDirectory()) imsi.addElement("<DIR>");

else if (f.isFile()) imsi.addElement("");

imsi.addElement(f.length() + "Bytes");

dataVector.addElement(imsi);

}

DefaultTableModel model = new DefaultTableModel(dataVector, columnVector);

this.right.getTable().setModel(model);

this.right.getCardLayout().show(this.right,"table");

}else if(file.isFile()){

BufferedReader br = null;

String line = "", line1 = "";

try{

br = new BufferedReader(new FileReader(file));

while((line = br.readLine()) != null){

line1 += line + "\n";

}

this.right.getTextArea().setText("");  //텍스트공간 초기화

this.right.getTextArea().append(line1);

this.right.getCardLayout().show(right, "area");

}catch (IOException e2){

JOptionPane.showMessageDialog(this.panel, e2.getMessage());

}finally{

try{

if(br != null) br.close();

}catch(IOException ex){}

}

}

}

}

----------------------------------------------------------

(참조)

1) 루트 디렉토리명만 출력하기(드라이브명)

File file[];

file = File.listRoots();

for(i =0 ; i<file.length ; i++)

{

    System.out.println(file[i].toString());

}

2) 특정 루트 디렉토리의 디렉토리만을 출력(특정 드라이브)

import java.io.*;

class rootDirectoryList

{

    public void list()

    {

        File root=new File("c:/");

        File file[]=root.listFiles();

        

        int i;

        for(i=0 ; i<file.length ; i++)

        {

            if(file[i].isDirectory())

            {

                System.out.println(file[i].toString());

            }

        }

        

    }

    

    public static void main(String args[])

    {

        rootDirectoryList l=new rootDirectoryList();

        l.list();

    }

}


출처:

http://cafe.naver.com/04itschool/299

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

직렬화

java.io.Serializable 의 자식은 직렬화가 가능.(오버라이드할 것이 하나도 없음)

preemitive 타입은 직렬화가 가능.

String, Vector, Date 는 Serializable 의 자식이므로 직렬화 가능.


import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

import java.util.Date;


public class SerializationDemo {

public static void main(String[] args) {

Date date = new Date();

System.out.println(date.toString());  //Tue Apr 01 16:05:46 KST 2014

ObjectOutputStream oos = null;

try{

String path = "/home/mino/Temp";

oos = new ObjectOutputStream(

new FileOutputStream(new File(path, "date.ser")));

oos.writeObject(date);

System.out.println("잘 저장됐습니다.");

}catch(IOException ex){

}finally{

try{

oos.close();

}catch(IOException ex){}

}

}

}

//만들어진 파일을 열면 제대로된 글자가 안나온다. 하지만 역직렬화를 통해 다시 불러오면 제대로보인다.

--------------------------------

역직렬화  - 직렬화한 것을 복원

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.util.Date;



public class SerializationDemo1 {

public static void main(String[] args) {

String path = "/home/mino/Temp";

ObjectInputStream ois = null;

try {

ois = new ObjectInputStream(new FileInputStream(new File(path, "date.ser")));

Object obj = ois.readObject();

if(obj instanceof Date){

Date before = (Date)obj;

System.out.println(before);

}

} catch (Exception e) {

} finally{

try {

if(ois != null) ois.close();

} catch (Exception e2) {}

}

}

}

출력:

Tue Apr 01 16:06:51 KST 2014

-------------------------------------------------------------

직렬화


public class Student implements java.io.Serializable { //이것을 implements 하지않으면 Student는 serializable하지 않기에 에러발생.

private String hakbun, name;

private int kor, eng, mat, edp;

public Student(String hakbun, String name, int kor, int eng, int mat,

int edp) {

super();

this.hakbun = hakbun;

this.name = name;

this.kor = kor;

this.eng = eng;

this.mat = mat;

this.edp = edp;

}

@Override

public String toString(){

return String.format("%-10s%10s%5d%5d%5d%5d",

             this.hakbun, this.name, this.kor, this.eng, this.mat, this.edp);

}

public String getHakbun() {

return hakbun;

}

public void setHakbun(String hakbun) {

this.hakbun = hakbun;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getKor() {

return kor;

}

public void setKor(int kor) {

this.kor = kor;

}

public int getEng() {

return eng;

}

public void setEng(int eng) {

this.eng = eng;

}

public int getMat() {

return mat;

}

public void setMat(int mat) {

this.mat = mat;

}

public int getEdp() {

return edp;

}

public void setEdp(int edp) {

this.edp = edp;

}

}






import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.util.Vector;


public class Input {

private Vector<Student> vector;


Input(Vector<Student> vector) {

this.vector = vector;

}

void input(){

BufferedReader br = null;

String line = null;

try{

String path = "/home/mino/Downloads/sungjuk_utf8.dat";

br = new BufferedReader(new FileReader(new File(path)));

while((line = br.readLine()) != null){

String [] array = line.split("\\s+");

Student s = new Student(array[0], array[1], Integer.parseInt(array[2]),

              Integer.parseInt(array[3]), Integer.parseInt(array[4]),

              Integer.parseInt(array[5]));

this.vector.addElement(s);

}

}catch(IOException ex){

}finally{

try{

if(br != null) br.close();

}catch(IOException ex){}

}

}

}






import java.io.File;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;

import java.util.Vector;



public class SerializationDemo2 {

public static void main(String[] args) throws Exception{

Vector<Student> vector = new Vector<Student>(1,1);

Input input = new Input(vector);

input.input();

String path = "/home/mino/Temp";

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(path, "student.ser")));

//객체의 직렬화는 reader와 writer를 쓰지않는다. byte를 쓰는 OutputStream을 사용한다.

oos.writeObject(vector);

System.out.println("Success");

oos.close();

}

}

-------------------------------

역직렬화

import java.io.File;

import java.io.FileInputStream;

import java.io.ObjectInputStream;

import java.util.Vector;



public class SerializationDemo3 {

public static void main(String[] args) throws Exception{

String path = "/home/mino/Temp";

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(path, "student.ser")));

Object obj = null;

obj = ois.readObject();

Vector<Student> vector = (Vector<Student>)obj;

//System.out.println(vector.size());

for(Student s : vector){

System.out.println(s);

}

ois.close();

}

}

출력:

1101             한송이   78   87   83   78

1102             정다워   88   83   57   98

1103             그리운   76   56   87   78

1104             고아라   83   57   88   73

1105             사랑해   87   87   53   55

1106             튼튼이   98   97   93   88

1107             한아름   68   67   83   89

1108             더크게   98   67   93   78

1109             더높이   88   99   53   88

1110             아리랑   68   79   63   66

1111             한산섬   98   89   73   78

1112             하나로   89   97   78   88

----------------------

만약 위에서 Student Class에서 

transient private String name; //transient를 쓰면 이것을 빼고 직렬화를 하겠다.

위와 같이 쓰면 아래와 같이 출력된다. 출력전에는 한번더 직렬화를 해주고 역직렬화를 실행해야 한다.

1101            null   78   87   83   78

1102            null   88   83   57   98

1103            null   76   56   87   78

1104            null   83   57   88   73

1105            null   87   87   53   55

1106            null   98   97   93   88

1107            null   68   67   83   89

1108            null   98   67   93   78

1109            null   88   99   53   88

1110            null   68   79   63   66

1111            null   98   89   73   78

1112            null   89   97   78   88


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

=======================================================================

java.net

1. OSI7 Layers - ISO

Application Layer

Presentation Layer

Session Layer

Transport Layer -> TCP, UDP

Network Layer --> IP

Datalink Layer --> MAC Address(물리적주소)

Phisical Layer


802Model - IEEE



2. TCP, UDP

TCP --> Connection Oriented Protocol  //확실히 전송되어 안정성이 필요한 곳에서 사용. 느림.

UDP --> Connection-less Protocol   //안정성보다 속도가 빨라야하는 곳에서 사용.


3. Socket

1)IP --> DNS(를통해 IP를 알아냄)

2)#Port

 - 0 ~ 1023 : Well-known Port Number.

 - 1024 ~ 2048 :Vendor Port.

 - 2049 ~ 65535 : User Port.



Inet Address

URL

URLConnection

URLEncode

URLDecode


ServerSocket

Socket


DatagramPacket

DatagramSocket

------------------------------------------

InetAddress

import java.net.InetAddress;

import java.net.UnknownHostException;

import java.util.Scanner;



public class InetAddressDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("Hostname : ");

String hostname = scan.next();

InetAddress ia = null;

try{

ia = InetAddress.getByName(hostname); //생성자가없어서 new 못씀  //단점: 하나만 읽어온다.

System.out.printf("%s --> %s\n", ia.getHostName(), ia.getHostAddress());

}catch(UnknownHostException ex){

System.out.println(ex.getMessage());

}

}

}

출력:

Hostname : www.naver.com

www.naver.com --> 202.131.30.11

출력:

Hostname : www.google.com

www.google.com --> 173.194.38.83

----------------------------------

쓰는 아이피 전체를 읽음.

import java.net.InetAddress;

import java.net.UnknownHostException;

import java.util.Scanner;


public class InetAddressDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("Hostname : ");

String hostname = scan.next();

InetAddress [] array = null;

try{

array = InetAddress.getAllByName(hostname);

for(InetAddress ia : array)

System.out.printf("%s --> %s\n", ia.getHostName(), ia.getHostAddress());

}catch(UnknownHostException ex){

System.out.println(ex.getMessage());

}

}

}

출력:

Hostname : www.naver.com

www.naver.com --> 202.131.30.12

www.naver.com --> 125.209.222.141

출력:

Hostname : www.google.com

www.google.com --> 173.194.117.243

www.google.com --> 173.194.117.242

www.google.com --> 173.194.117.240

www.google.com --> 173.194.117.244

www.google.com --> 173.194.117.241

www.google.com --> 2404:6800:4004:807:0:0:0:1013

----------------------------------------------------

자기 컴퓨터의 호스트이름과 아이피를 출력하는 소스

import java.net.InetAddress;

import java.net.UnknownHostException;


public class InetAddressDemo1 {

public static void main(String[] args) throws UnknownHostException{

InetAddress ia = null;

ia = InetAddress.getLocalHost();

System.out.println(ia.getHostName() + "  --> " + ia.getHostAddress());

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

====================================================================

VMware Workstation 깔아서 윈도우 깔기.

http://www.vmware.com/ 이동. 다운로드 탭에서 VMware Workstation 눌러줌.

VMware Workstation 10 for Linux 32-bit 다운로드.

다운받은 파일은 실행파일이 아니기 때문에 터미널에서 chmod +x VMware*.i386.bundle로 실행되게 해줌.

그리고 sudo apt-get update 로 캐시 업데이트 후.

sudo apt-get install build-essential linux-headers-$(uname -r) 해서 설치.

gksudo bash ./VMware*.i386.bundle 로 설치하는데, next 누르다가 시작시업데이트 Yes 누르고 다음은 NO 한번 눌러주고  계속 next

체험판을 쓸것이기때문에 시리얼넘버는 안넣어줌.

그리고 윈도우 설치.


vmware workstation으로 윈도우 부팅시 한글 적용.

/etc/vmware 의 config 파일을 sudo gedit config 로 열어서 제일 아랫줄에 추가

xkeymap.keysym.Hangul = 0x0f2

xkeymap.keysym.Hangul_Hanja = 0x0f1


우분투 한글

터미널에서 sudo gedit ~/.Xmodmap 열어서

keycode 122 = Hangul

keycode 121 = Hangul_Hanja

추가 후 재부팅. (파일이 없으면 그냥 열어줌)

+ Recent posts