레이블이 JDK설치인 게시물을 표시합니다. 모든 게시물 표시
레이블이 JDK설치인 게시물을 표시합니다. 모든 게시물 표시

2013년 8월 2일 금요일

JAVA RandomAccessFile (자바 랜덤파일처리)

임의의 바이트, 텍스트등을 파일내 임의의 위치에 쓸수 있도록 허락
InputStream이나 OutputStream의 서브 클래스는 아니지만 파일의 읽기, 쓰기를 위한 독립적인 메소드를 제공한다. 


 오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의) 

length() : 파일의 길이 
getFilePointer() : 현재 포인터의 위치 
seek() : 포인터 위치 설정 
readBoolean(), readByte(),readChar(), readShort(), readLong(), readInt(), readFloat(),readDouble(), readLine(), readUTF() : 해당타입의 데이터 읽기 
writeBoolean(), writeByte(),writeChar(), writeShort(), writeLong(), writeInt(), writeFloat(), writeDouble(), writeUTF() : 해당타입의 데이터 쓰기 
close() : 파일 닫기 



import java.io.*; class RandomTest { public static void main(String[] args) throws IOException {      RandomAccessFile raf=new 
                            RandomAccessFile("test.txt","rw");      raf.seek(raf.length());      raf.writeUTF("The end");      raf.close(); } }



----------------
메모장 –  예제
----------------
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class NotePad extends Frame implements ActionListener {
TextArea text = null;
String filename = null;

public NotePad(String title) {
    super(title); // set title
    MenuBar menuBar=new MenuBar();
    Menu fileMenu = new Menu("File");
    menuBar.add(fileMenu);
    MenuItem openItem = new MenuItem("Open...", new MenuShortcut('O'));
    openItem.setActionCommand("Open"); // for getActionCommand
    openItem.addActionListener(this);
    fileMenu.add(openItem);


    MenuItem saveItem = new MenuItem("Save", new MenuShortcut('S'));
    saveItem.setActionCommand("Save"); // for getActionCommand
    saveItem.addActionListener(this);
    fileMenu.add(saveItem);
    MenuItem saveasItem = new MenuItem("Save As...", new MenuShortcut('V'));
    saveasItem.setActionCommand("SaveAs"); // for getActionCommand
    saveasItem.addActionListener(this);
    fileMenu.add(saveasItem);
    fileMenu.addSeparator();
    MenuItem exitItem = new MenuItem("Exit", new MenuShortcut('X'));
    exitItem.setActionCommand("Exit"); // for getActionCommand
    exitItem.addActionListener(this);
    fileMenu.add(exitItem);
    setMenuBar(menuBar);
    text = new TextArea();   


    add(text, "Center");
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            dispose();
            System.exit(0);
        }
    });
    setSize(500, 400);    setVisible(true);
}
public static void main(String args[]) throws Exception {
    new NotePad("Simple NotePad...");
}
public void actionPerformed(ActionEvent e) {
    String cmd=e.getActionCommand();
    if (cmd.equals("Exit"))
        System.exit(0);
    else if (cmd.equals("Open")) {
        FileDialog dialog=new FileDialog(this, "Text File Open", FileDialog.LOAD);
        dialog.show(); // file dialog is modal
        String filename=dialog.getFile();


      if (filename != null) {
            String directory=dialog.getDirectory();
            if (directory != null)
                filename=directory+filename;
            loadFile(filename);
        }
    }
    else if (cmd.equals("Save")) {
        if (this.filename != null) saveFile(this.filename);
        else {
            FileDialog dialog=new FileDialog(this, "Text File Save", FileDialog.SAVE);
            dialog.show(); // file dialog is modal
            String filename=dialog.getFile();
            if (filename != null) {
                String directory=dialog.getDirectory();
                if (directory != null)
                    filename=directory+filename;
                saveFile(filename);
            }
        }
    }


else if (cmd.equals("SaveAs")) {
        FileDialog dialog=new FileDialog(this, "Text File Save", FileDialog.SAVE);
        dialog.show(); // file dialog is modal
        String filename=dialog.getFile();
        if (filename != null) {
            String directory=dialog.getDirectory();
            if (directory != null)
                filename=directory+filename;
            saveFile(filename);
        }
    }
}


private void loadFile(String filename) {
    BufferedReader in = null; 
    text.setText("");

    try {
        in = new BufferedReader(new FileReader(filename),1024); 
        String string=null;


      while ((string=in.readLine()) != null) {  text.append(string+'\n');    }
        in.close();
    } 
    catch (IOException ie) {System.err.println("File Read Error : "+ie.getMessage()); }
    setTitle("FileName:"+filename);
    this.filename=filename;
}
private void saveFile(String filename) {
    BufferedWriter out = null; 
    try {
        out = new BufferedWriter(new FileWriter(filename));
      String string=text.getText();
        out.write(string); 
      out.close();
  }
    catch(IOException e) { System.err.println("File Read Error : "+e.getMessage()); }
    setTitle("FileName:"+filename);
    this.filename=filename;
}
}

2013년 7월 28일 일요일

(오라클자바개발자실무교육,오엔제이프로그래밍실무교육센터)자바 리플렉션(JAVA Reflection)에 대해 ,

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷  실무전문 강의)


Runtime에 클래스를 전달받아서 임의의 method를 실행하는 시스템이 있다고 가정하면 이 때 전달되는 파라미터, return되는 파라미터 모두 개발당시에는 알지 못한다고 하자 이러한 시스템에는 임의의 클래스가 주어졌을 때, 그 클래스에 대한 정보, 다시 말해서 해당 클래스의 생성자 (constructor), 멤버변수, method, 슈퍼 클래스 , 상위 인터페이스에 대한 정보를 얻을 수 있는 기능이 필요하다 이렇게 임의의 클래스에 대한 정보를 얻을 수 있게 해 주는 API가 바로 reflection API이다. 

Ex) import java.lang.reflect.*;
    Object o;
    Class c = o.getClass();
    ……
    Method m = c.getMethod(“setText”, new Class[] {String.class} );
    ……


import java.lang.reflect.*;
import java.awt.*;
class ReflectionTest {

public static void main(String[] args) {
      Button b = new Button();
      getNameSuperClass(b);
}
static void getNameSuperClass(Object o) {
      Class c = o.getClass();
      String s = c.getName();
      String s1 = c.getSuperclass().toString();
      System.out.println(s + "\n" + s1);
  }
}
 
 

(오라클자바개발자실무교육,오엔제이프로그래밍실무교육센터)JAVA Nateive Thread/Green Thread 선점형/비선점형

Sun의 JDK 1.2/1.3에는 JIT(just-In-time) 기술이 도입되어 loading 시점에  바이트코드를 실제 기계에서 수행되는 코드로 바꾼 후 실행하게 함으로써 상당한 성능 향상을 가져왔다 
네이티브와 그린 쓰레드는 자바에서 사용되는 쓰레드의 실제 구현상의 차이를 나타내는 것이다. 쓰레드를 자바 가상 기계 내에서 처리하는 것이 그린 쓰레드이고, 커널의 쓰레드 지원 기능을 이용하는 것이 네이티브 쓰레드이다.


  오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷  실무전문 강의)




비선점형(Non-preemptive)멀티태스킹 :운영체제가 제어권을 가지고 있지 않고 응용 프로그램이 제어권을 가지고 있는 것으로 응용 프로그램이 제어권을 운영체제로 돌려주지 않고 중앙 처리 장치를 독점하면 컴퓨터가 다운되는 현상이 생길 수 있다.(Win3.1, MacOS)

선점형(preemptive) 멀티태스킹 : 운영체제가 제어권을 응용 프로그램에게 부여하는 것으로 응용 프로그램이 제어권을 독점하는 것을 방지하여 안정적인 작업 환경을 지원하는 체제이다.(Win95/98, WinNT, Unix)