Java 文件操作简单demo

两小时写了这么一个小的demo,不过很惭愧的说,里面有一点bug,程序有时工作有时又不太工作……不过初学者还可以看看的说……如果有大牛能够指出到底哪有问题,必定感激不尽。

界面大致如下所示:


共有两个源文件,Frame.java

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


/**
 * 
 * @author lwfcgz
 *
 */
public class Frame extends JFrame{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel northPanel,southPanel;
	private TextArea textArea;
	private JButton openButton;
	private JButton createButton;
	private JButton deleteButton;
	private JButton closeButton;
	private JButton readButton;
	private JButton writeButton;
	private JButton pointerButton;
	private JButton propertyButton;
	private File file;
	private JFileChooser fileChooser;
	private RandomAccessFile randomAccessFile;
	private int screenWidth,screenHeight;
	private int frameWidth,frameHeight;
	private String path;
	private String content;
	
//	constructor
	public Frame(){
		this.northPanel=new JPanel(new BorderLayout());
		this.southPanel=new JPanel(new GridLayout(2,4));	
		this.fileChooser=new JFileChooser();
		this.fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		
//		set property of north panel
		this.textArea=new TextArea("", 10, 70,TextArea.SCROLLBARS_BOTH);
		this.textArea.setEditable(false);
		this.textArea.setText("");		
		this.northPanel.add(this.textArea,BorderLayout.CENTER);
		
//		set property of south panel
		this.openButton=new JButton("打开");
		this.openButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				int result=fileChooser.showOpenDialog(null);				
				if((result==JFileChooser.APPROVE_OPTION)){
					file=fileChooser.getSelectedFile();
					try {
						if(randomAccessFile!=null)
							randomAccessFile.close();
						randomAccessFile=new RandomAccessFile(file,"rw");
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					path=fileChooser.getSelectedFile().getAbsolutePath();
					textArea.setText("已打开文件: "+path);
				}
			}
			
		});//end openButton action listener
		this.southPanel.add(openButton);
		this.createButton=new JButton("创建");
		this.createButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String tmpPath=JOptionPane.showInputDialog(null, "请输入新建文件名", "创建文件", JOptionPane.INFORMATION_MESSAGE);
				if(tmpPath==null){
					JOptionPane.showMessageDialog(null, "创建新文件失败", "Error", JOptionPane.ERROR_MESSAGE);
				}
				else{
					path=tmpPath;
					textArea.setText("已创建新文件"+path);					
					file=new File(path);
					try {
						if(randomAccessFile!=null)
							randomAccessFile.close();
						randomAccessFile=null;
						randomAccessFile=new RandomAccessFile(file,"rw");
					} catch (FileNotFoundException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
						file.createNewFile();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}//end try catch
				}//end else
			}//end method action performed
			
		});//end createButton action listener
		this.southPanel.add(createButton);
		this.deleteButton=new JButton("删除");
		this.deleteButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(file==null){
					JOptionPane.showMessageDialog(null, "当前文件为空", "Error", JOptionPane.ERROR_MESSAGE);
					textArea.setText("删除文件失败");
					return;
				}
				if(randomAccessFile!=null)
					try {
						randomAccessFile.close();
						randomAccessFile=null;
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				file=new File(path);
				if(file.delete()==true){
					textArea.setText("已成功删除文件"+path);
					path=null;
					file=null;				
				}
				else{
					textArea.setText("由于未知原因,删除文件失败"+path);
				}
			}//end method actionPerformed
			
		});//end action listener for delete button
		this.southPanel.add(deleteButton);
		this.closeButton=new JButton("关闭");
		this.closeButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(file==null){
					JOptionPane.showMessageDialog(null, "当前文件为空", "Error", JOptionPane.ERROR_MESSAGE);
					textArea.setText("关闭文件失败");
					return;
				}
				else{
					JOptionPane.showMessageDialog(null, "成功关闭文件", "Info", JOptionPane.INFORMATION_MESSAGE);
					try {
						if(randomAccessFile!=null)
							randomAccessFile.close();
						randomAccessFile=null;
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					file=null;
					path=null;
					textArea.setText("");
				}
			}//end method actionPerformed
			
		});//end closeButton action listener
		this.southPanel.add(closeButton);
		this.readButton=new JButton("读取");
		this.readButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(file==null){
					JOptionPane.showMessageDialog(null, "当前文件为空", "Error", JOptionPane.ERROR_MESSAGE);
					textArea.setText("读取文件失败");
					return;
				}
				try {
					if(randomAccessFile==null)
						randomAccessFile=new RandomAccessFile(file,"rw");
				} catch (FileNotFoundException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
				content="";
				byte[] buffer=new byte[5000];
				int hasRead=0;
				try {
					while((hasRead=randomAccessFile.read(buffer))>0){
						content+=new String(buffer,0,hasRead);
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				textArea.setText(content);
			}//end method action performed
			
		});//end read button action listener
		this.southPanel.add(readButton);
		this.writeButton=new JButton("写入");
		this.writeButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(file==null){
					JOptionPane.showMessageDialog(null, "当前文件为空", "Error", JOptionPane.ERROR_MESSAGE);
					textArea.setText("写入文件失败");
					return;
				}
				try {
					if(randomAccessFile==null)
						randomAccessFile=new RandomAccessFile(file,"rw");
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				String tmp=JOptionPane.showInputDialog(null,"请输入要写的内容","输入",JOptionPane.INFORMATION_MESSAGE);
				if(tmp==null || tmp.length()==0){
					JOptionPane.showMessageDialog(null, "没有要写入的内容", "Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				try {
					randomAccessFile.seek(file.length());
					randomAccessFile.write(tmp.getBytes());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}				
				textArea.setText("已成功写入文件:"+file.getName());
			}//end method action performed
			
		});//end write button action listener
		this.southPanel.add(writeButton);
		this.pointerButton=new JButton("定位");
		this.pointerButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(file==null){
					JOptionPane.showMessageDialog(null, "当前文件为空", "Error", JOptionPane.ERROR_MESSAGE);
					textArea.setText("定位文件失败");
					return;
				}
//				get user's input value
				String tmp=JOptionPane.showInputDialog(null,"请输入定位目标","指针定位",JOptionPane.INFORMATION_MESSAGE);
				int result=Integer.valueOf(tmp).intValue();
				if(result<0 || result>file.length()){
					JOptionPane.showMessageDialog(null, "无效指针位置", "Error", JOptionPane.ERROR_MESSAGE);
					textArea.setText("定位文件失败");
					return;
				}
				try {
					if(randomAccessFile==null)
						randomAccessFile=new RandomAccessFile(file,"rw");
					randomAccessFile.seek(result);					
					textArea.setText("定位文件成功"+'\n'+"当前指针位置:"+result);
					JOptionPane.showMessageDialog(null, "成功定位指针位置", "Info", JOptionPane.INFORMATION_MESSAGE);
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}//end method action performed
			
		});//end pointer button listener
		this.southPanel.add(pointerButton);
		this.propertyButton=new JButton("属性");
		this.propertyButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(file==null){
					JOptionPane.showMessageDialog(null, "当前文件为空", "Error", JOptionPane.ERROR_MESSAGE);
					textArea.setText("文件属性查看失败");
					return;
				}
				else{
					textArea.setText("文件名:"+file.getName()+'\n'
							+"文件长度:"+file.length()+'\n'
							+"文件路径:"+file.getAbsolutePath()+'\n'
							+"最后修改日期:"+file.lastModified()+'\n'
							+"文件可读性:"+file.canRead()+'\n'
							+"文件可写性:"+file.canWrite()+'\n');
				}
			}//end method action performed
			
		});//end property button action listener
		this.southPanel.add(propertyButton);
		
//		add panels into frame
		this.frameHeight=300;
		this.frameWidth=350;
		this.add(northPanel,BorderLayout.NORTH);
		this.add(this.southPanel,BorderLayout.SOUTH);
		this.setSize(this.frameWidth,this.frameHeight);
		this.setTitle("Demo by lwfcgz");
		
//      get screen size and set the location in the center of the screen
        this.screenWidth=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        this.screenHeight=(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        this.setLocation((this.screenWidth-this.frameWidth)/2, (this.screenHeight-this.frameHeight)/2);
        this.setVisible(true);
        
	}//end constructor

}//end class Frame


Main.java
import javax.swing.JFrame;


/**
 * 
 * @author lwfcgz
 *
 */
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Frame frame=new Frame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}//end method main

}//end class Main


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值