java如何filechooser选择盘_YFileChooser-Java文件选取

?package com.chris.base;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.IOException;

import java.util.Properties;

import javax.swing.JFileChooser;

public class YFileChooser {

private Properties profile;

private String profileName = "FileInfo.properties";

private final String LAST_DIR_TAG = "LAST_DIR";

private String lastDir;

private JFileChooser jfc = new JFileChooser();// 文件选择器

public YFileChooser() {

// 创建一个Properties对象,用于获取/保存上一次选中文件的路径

profile = new Properties();

try {

// 配置Properties对象获取的配置文件的文件名

profile.load(new BufferedInputStream(new FileInputStream(profileName)));

// 尝试获取上一次路径,如果没有成功,就得到"."

lastDir = profile.getProperty(LAST_DIR_TAG, ".");

} catch (FileNotFoundException e) {

System.out.println("找不到配置文件");

lastDir = ".";

} catch (IOException e) {

System.out.println("读取配置文件失败");

lastDir = ".";

}

}

public File getSelectedFile() {

File selectedFile = null;

// 根据此前的到的lastDir(路径),设置文件选择器打开的默认路径

jfc.setCurrentDirectory(new File(lastDir));

// 配置文件选择器筛选的模式,FILES_ONLY:只可选文件,不可选目录

jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);

// 打开文件选择器的选择页面

int state = jfc.showOpenDialog(null);

// state返回JFileChooser.APPROVE_OPTION就表示成功选择文件

if (JFileChooser.APPROVE_OPTION == state) {

// 获取得到文件的File对象

selectedFile = jfc.getSelectedFile();

// 获取文件的绝对路径

String path = selectedFile.getAbsolutePath();

// 获取目录部分,省略文件名

path = path.substring(0, http://www.doczj.com/doc/3ddc685e69dc5022abea0011.htmlstIndexOf("\\"));

// 上面就得到了本次打开的文件的路径,保存到profile中,用于下一次选文件时,打开这个目录

try {

if (!path.equals(lastDir)) {

profile.put(LAST_DIR_TAG, path);

profile.store(new BufferedOutputStream(new FileOutputStream(profileName)), "By hzm");

System.out.println("保存当前路径成功");

}

} catch (FileNotFoundException e) {

System.out.println("创建配置文件失败");

} catch (IOException e) {

System.out.println("保存配置文件失败");

}

} else {

System.out.println("取消任务");

}

return selectedFile;

}

public static void main(String[] args) {

BufferedReader bReader;

YFileChooser fileChooser = new YFileChooser();

File selectedFile = fileChooser.getSelectedFile();

if (selectedFile != null) {

try {

bReader = new BufferedReader(new FileR

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值