代码改变世界

几个文件操作的小例子

2011-09-25 07:49  Rollen Holt  阅读(1591)  评论(0编辑  收藏  举报

最近一直在学习java web方面的东西,本来想完整的写一篇java web方面的文章,但是那一块太杂了,自己现在也不是很清晰,主要是myeclipse+Tomcat,每次启动tomcat都要花很长的时间,所以java web方面的文章目前还没有写,今天就先将自己之前的东西贴出来吧、

【案例1】获取文件的属性

运行结果:

代码如下:

/**
 * 获取文件属性
 * */

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MdifyfileAttribute extends JFrame implements ActionListener{
	JButton chooseButton = new JButton("浏览...");
	JLabel nameLabel = new JLabel();
	JLabel sizelabel = new JLabel("文件大小");
	JLabel pathLabel = new JLabel("文件路径");
	JLabel uriLabel = new JLabel("URI路径");
	JLabel datelabel = new JLabel("最后修改日期");

	JTextField sizeField = new JTextField(30);
	JTextField pathField = new JTextField(30);
	JTextField uriField = new JTextField(30);
	JTextField dateField = new JTextField(30);

	JCheckBox readCheckBox = new JCheckBox("可读");
	JCheckBox writeCheckBox = new JCheckBox("可写");
	JCheckBox hideCheckBox = new JCheckBox("隐藏");

	JPanel panel = new JPanel();

	public MdifyfileAttribute(){
		panel.setLayout(new FlowLayout());
		panel.add(chooseButton);
		panel.add(nameLabel);
		panel.add(sizelabel);
		panel.add(sizeField);
		panel.add(pathLabel);
		panel.add(pathField);
		panel.add(uriLabel);
		panel.add(uriField);
		panel.add(datelabel);
		panel.add(dateField);
		JPanel checkPanel = new JPanel();
		checkPanel.add(readCheckBox);
		checkPanel.add(writeCheckBox);
		checkPanel.add(hideCheckBox);
		panel.add(checkPanel);
		setContentPane(panel);

		chooseButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e){
				JFileChooser chooser = new JFileChooser();
				// 显示文件选择对话框
				chooser.showOpenDialog(MdifyfileAttribute.this);
				File file = chooser.getSelectedFile();
				if(file != null){
					nameLabel.setText(file.getName());
					sizeField.setText(file.length() + "");
					pathField.setText(file.getPath());
					uriField.setText(file.toURI() + "");
					dateField.setText(new Date(file.lastModified()) + "");
					readCheckBox.setSelected(file.canRead());
					writeCheckBox.setSelected(file.canWrite());
					hideCheckBox.setSelected(file.isHidden());
				}
			}
		});
		setSize(400, 400);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

	public static void main(String[] args){
		new MdifyfileAttribute();
	}
}

显示指定类型的文件

运行结果:

代码如下:

package File;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ListCustomTypeFile extends JFrame implements ActionListener{
	JPanel panel = new JPanel();
	JButton chooseButton = new JButton("选择文件夹");
	JLabel pathLabel = new JLabel();
	JLabel textLabel = new JLabel("请输入指定的文件扩展名");
	JTextField textField = new JTextField(20);
	JTextArea area = new JTextArea(5, 30);
	File dir = null;

	ListCustomTypeFile(){
		panel.setLayout(new FlowLayout());
		panel.add(chooseButton);
		panel.add(pathLabel);
		panel.add(textLabel);
		panel.add(textField);
		panel.add(area);
		setContentPane(panel);
		chooseButton.addActionListener(this);

		setSize(400, 400);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	@Override
	public void actionPerformed(ActionEvent e){
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		chooser.showDialog(this, null);
		dir = chooser.getSelectedFile();
		pathLabel.setText(dir.toString());
		listFiles();
	}

	public void listFiles(){
		if(dir == null){
			return;
		}
		// 获取符合条件的文件数组
		File[] files = dir.listFiles(new CustomFilter());
		String str = "文件名" + "\t\t" + "文件大小" + "\t\t" + "最后修改日期\n";
		area.setText(str);
		for(File temp : files){
			str += temp.getName() + "\t\t" + temp.length() + "\t\t"
					+ new Date(temp.lastModified()) + "\n";
			area.setText(str);
		}
	}

	public final class CustomFilter implements FileFilter{
		@Override
		public boolean accept(File pathname){
			// 获取用户设定的指定扩展名
			String name = textField.getText();
			if(name == null || name.isEmpty()){
				return false;
			}
			if(!name.startsWith(".")){
				name = "." + name;
			}
			name = name.toLowerCase();
			if(pathname.getName().toLowerCase().endsWith(name)){
				return true;
			}else{
				return false;
			}
		}
	}// end inner class

	public static void main(String[] args){
		new ListCustomTypeFile();
	}
}

下面打算以树结构显示文件目录:

先来个热身吧,先实现下面的图像再说,回忆一下Jtree的用法。其实主要是我对swing不熟悉,哈哈。

代码

代码如下:

package File;

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;

public class TreeSimple extends JFrame{
	public TreeSimple(){
		JPanel panel = new JPanel();
		JTextArea area = new JTextArea(5, 30);
		JTree tree = new JTree();
		JScrollPane js1 = new JScrollPane(tree,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		panel.setLayout(new FlowLayout());
		JScrollPane js = new JScrollPane(area);
		JSplitPane jsplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
				js1, js);
		panel.add(jsplit);
		setContentPane(panel);
		setSize(400, 400);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public static void main(String[] args){
		new TreeSimple();
	}
}

下面获取文件文件目录树

运行结果如下:

package File;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

public class Disktree extends JFrame implements TreeSelectionListener{
	DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
	JTree tree = new JTree(rootNode);
	JPanel panel = new JPanel();

	public Disktree(){
		tree.addTreeSelectionListener(this);
		JScrollPane js = new JScrollPane(tree,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		panel.add(tree);
		setContentPane(panel);

		addWindowListener(new WindowAdapter(){
			@Override
			public void windowActivated(WindowEvent e){
				File[] files = File.listRoots();
				for(File file : files){
					DefaultMutableTreeNode node = new DefaultMutableTreeNode(
							file);
					rootNode.add(node);
				}
				tree.expandPath(new TreePath(rootNode));
			}
		});

		setSize(500, 500);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public static void main(String[] args){
		new Disktree();
	}

	@Override
	public void valueChanged(TreeSelectionEvent e){
		TreePath path = e.getPath();
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
				.getLastPathComponent();

		Object userObject = node.getUserObject();
		if(!(userObject instanceof File)){
			return;
		}
		File folder = (File) userObject;
		if(!folder.isDirectory()){
			return;
		}
		File[] files = folder.listFiles();
		for(File file : files){
			node.add(new DefaultMutableTreeNode(file));
		}

	}
}

查找替换文本文件内容

运行结果

package File;

import java.awt.Desktop;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * 查找替换文本文件的内容
 * */
public class ReplaceFileText extends JFrame{
	JPanel panel = new JPanel();
	JButton chooseButton = new JButton("浏览文件");
	JTextField pathField = new JTextField(20);
	JLabel searchlabel = new JLabel("搜索文本:");
	JTextField searchField = new JTextField(20);
	JLabel replaceLabel = new JLabel("替换为:");
	JTextField replaceField = new JTextField(20);
	JButton replaceButton = new JButton("替换");
	JButton openButton = new JButton("打开查看文件");
	File file = null; // 保存选择的文件

	public ReplaceFileText(){
		init();
		setSize(400, 400);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

	private void init(){
		panel.setLayout(new GridLayout(4, 2));
		panel.add(chooseButton);
		panel.add(pathField);
		panel.add(searchlabel);
		panel.add(searchField);
		panel.add(replaceLabel);
		panel.add(replaceField);
		panel.add(replaceButton);
		panel.add(openButton);
		setContentPane(panel);

		chooseButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e){
				chooseButton_event();
			}
		});
		replaceButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e){
				replaceButton_event();
			}
		});

		openButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e){
				openButton_event();
			}
		});

	}

	/**
	 * 选择文件按钮事件处理
	 * */
	public void chooseButton_event(){
		JFileChooser chooser = new JFileChooser();
		// 设置文件扩展名过滤器
		chooser.setFileFilter(new FileNameExtensionFilter("文本文件", "txt",
				"java", "py", "html"));
		// 设置文件选择模式
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		// 显示文件选择对话框
		int option = chooser.showOpenDialog(this);
		// 确定用户按下打开按钮,而不是取消按钮
		if(option != JFileChooser.APPROVE_OPTION){
			return;
		}
		// 获取用户选择的文件
		file = chooser.getSelectedFile();
		// 设置文件路径
		pathField.setText(file.getPath());
	}

	/**
	 * 替换按钮事件处理
	 * */
	public void replaceButton_event(){
		String searchStr = searchField.getText();
		String replaceStr = replaceField.getText();
		if(searchStr == null || replaceStr == null){
			return;
		}
		try{
			FileReader reader = new FileReader(file);
			char[] dates = new char[1024];
			int count = 0;
			StringBuilder sb = new StringBuilder();
			while((count = reader.read(dates)) > 0){
				String str = String.valueOf(dates, 0, count);
				sb.append(str);
			}
			reader.close();
			// 从构造器中生成字符串,并替换搜索文本
			String str = sb.toString().replace(searchStr, replaceStr);
			FileWriter writer = new FileWriter(file);
			writer.write(str.toCharArray());
			writer.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		JOptionPane.showMessageDialog(null, "替换完成");
	}

	/**
	 * 打开文件按钮事件处理
	 * */
	public void openButton_event(){
		Desktop desktop = Desktop.getDesktop();
		if(desktop.isDesktopSupported()){
			try{
				desktop.open(file);
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args){
		new ReplaceFileText();
	}
}