Linux教程網
Java 用文件對話框打開文件:
- //文件的打開
- import java.awt.FileDialog;
- import java.awt.event.*;
- import java.io.*;
- import java.io.File;
- import java.io.FileReader;
-
- public class FileOpen {
- private FileDialog filedialog_open;
- private String fileopen = null, filename = null;// 用於存放打開文件地址 和文件名
- private File file1; // 文件字節流對象
- private FileReader file_reader;//文件字符流對象
- private BufferedReader in;//文件行讀取 寫入對象
- private StringBuffer text = new StringBuffer();
-
- HaffmanFrame haffman= null;
- FileOpen(HaffmanFrame hf) {
- haffman = hf;
- filedialog_open = new FileDialog(haffman, "打開文件對話框", FileDialog.LOAD);
- // 打開文件對話框適配器
- filedialog_open.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- filedialog_open.setVisible(false);
- }
- });
- }
-
- public void open() {
- String s = "";
- filedialog_open.setVisible(true);
- fileopen = filedialog_open.getDirectory();// 返回文件對話框中顯示的文件所屬的目錄
- filename = filedialog_open.getFile();// 返回當前文件對話框中顯示的文件名的字符串表示
- // 如果不存在就返回NULL
- if (filename != null)// 判斷打開的文件是否存在
- {
- try {
- file1 = new File(fileopen,filename );
- file_reader = new FileReader(file1);
- in = new BufferedReader(file_reader);//每次讀取一行
- while ((s = in.readLine()) != null)
- text.append(s + '/n');
- in.close();
- file_reader.close();
- } catch (IOException e2) {
- System.out.println("不能打開文件!");
- }
- }
- }
- //返回得到的文本字符串
- public String getText() {
- return new String(text);
- }
- }
Copyright ©
Linux教程網 All Rights Reserved