要求:设计如下界面
  文本框里面可以输入的路径和文件名
  单机按钮可以读取在 指定的文件
  并把文件内容显示到一个文本域里面来

 

代码:

/**
 * 
 */
package com.niit.homework;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * @author: Annie
 * @date:2016年6月16日
 * @description:2设计如下界面
                                                文本框里面可以输入的路径和文件名
                                                单机按钮可以读取在 指定的文件
                                               并把文件内容显示到一个文本域里面来
 */
public class IoDemo extends JFrame implements ActionListener{

    JTextField jt_path;
    JTextArea ja;
    JLabel lab_adrr;
    JButton button;


    public IoDemo() {
        super("读取文件");
        setLayout(new FlowLayout());
        setSize(380,380);
        jt_path = new JTextField(15);
        ja = new JTextArea(15,25);
        button = new JButton("确定");

        button.addActionListener(this);

        add(new JLabel("请输入文件地址"));
        add(jt_path);
        add(button);
        add(new JScrollPane(ja));
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    public static void main(String[] args) {
        IoDemo ioDemo = new IoDemo();

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int data;
        String path = jt_path.getText().trim();//读取到文件名
        System.out.println(path);
        //读取文件内容
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            byte [] a = new byte[1024];
            while((data =fis.read(a,0,1024))!=-1){
                
               String str = new String(a,0,data);
               ja.append(str);
            }
        } catch ( IOException e1) {}
        finally{
            try {
                fis.close();
            } catch (IOException e1) {
            }
        }
        
    }

}

 

注意: E:\\files\\niit.txt 要在你的E盘里先创建files包和niit.txt文件。并在.txt文件里写上文字。

效果图:

posted on 2016-06-16 15:00  王铭霞  阅读(256)  评论(0编辑  收藏  举报