파일 선택 다이얼 로그는 파일 탐색기를 띄워서 파일을 선택하거나 내용을 파일로 저장할 수 있습니다.


showOpenDialog() 파일 열기

파일 탐색기를 통해 파일을 선택합니다.


// ex.1)
import javax.swing.JFileChooser;
 
public class Ex06 {
             
    public Ex06() {
        JFileChooser jfc = new JFileChooser();
        int returnVal = jfc.showOpenDialog(null);
        if(returnVal == 0) {
            System.out.println("파일 열기를 선택했습니다.");
        }
        else
        {
            System.out.println("파일 열기를 취소하였습니다.");
        }
    }
    public static void main(String[] args) {
        new Ex06();
    }
}


다음은 선택한 파일의 내용을 읽어 보겠습니다. 

// ex.2)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
 
import javax.swing.JFileChooser;
 
public class Ex06 {
             
    public Ex06() {
        JFileChooser jfc = new JFileChooser();
        int returnVal = jfc.showSaveDialog(null);
        if(returnVal == 0) {
            File file = jfc.getSelectedFile();
            try {
                String tmp, str = null;
                BufferedReader br = new BufferedReader(new FileReader(file));
                while((tmp = br.readLine()) != null)
                {
                    str += tmp;
                }
                System.out.println(str);
            }catch(Exception e) {
                e.printStackTrace();
            }
             
        }
        else
        {
            System.out.println("파일 열기를 취소하였습니다.");
        }
    }
    public static void main(String[] args) {
        new Ex06();
    }
}



showSaveDialog() 파일 저장

내용을 파일로 저장합니다.

 

// ex.3)
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
 
import javax.swing.JFileChooser;
 
public class Ex06 {
             
    public Ex06() {
        JFileChooser jfc = new JFileChooser();
        int returnVal = jfc.showSaveDialog(null);
        if(returnVal == 0) {
            File file = jfc.getSelectedFile();
            System.out.println("당신이 저장할 파일은 " + file.getName() + " 입니다.");
             
            String str = "안녕하세요. 자바입니다.";
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                bw.write(str);
                bw.flush();
                bw.close();
                 
            }catch(Exception e) {e.printStackTrace();}
             
        }
         
    }
    public static void main(String[] args) {
        new Ex06();
    }
}


0 댓글