选择文件与获取选中文件绝对路径

	public static void main(String[] args) {
		JFrame frame = new JFrame();
		JButton button = new JButton("上传");
		frame.add(button);
		frame.setVisible(true);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 按钮点击事件

				JFileChooser chooser = new JFileChooser(); // 设置选择器
				chooser.setMultiSelectionEnabled(false); // 设为单选
				int returnVal = chooser.showOpenDialog(button); // 是否打开文件选择框
				System.out.println("returnVal=" + returnVal);

				if (returnVal == JFileChooser.APPROVE_OPTION) { // 如果符合文件类型

					String filepath = chooser.getSelectedFile().getAbsolutePath(); // 获取绝对路径
					System.out.println(filepath);

					System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); // 输出相对路径

				}
			}
		});
	}

你可能感兴趣的:(杂)