java 打开保存文件_基本操作--打开/保存文件

[java]代码库package s0201文件保存框保存文件;

import java.awt.*; //为了使用布局管理器

import java.awt.event.*;//用来处理事件

import javax.swing.*; //最新的GUI组件

import java.io.*; //读写文件用

public class filechooser {

public static void main(String[] args) throws IOException {

new filechooser();

}

private JFrame jframe;

private JPanel p;

private File file;

private JFileChooser jFileChooser;

private int flag;

boolean flag1 = false;

// 界面*********************************************************************

public filechooser() throws IOException

{

jFileChooser = new JFileChooser();

p = new JPanel()

{{add(new JButton("open"){{addActionListener((e) -> openFile());}});

add(new JButton("save"){{addActionListener((e) -> saveFile());}});

}};

jframe = new JFrame("java")

{{

setLayout(new FlowLayout());

add(p);

setSize(300, 300);

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}};

}

// 界面*********************************************************************

private void openFile()

{

// jFileChooser.setDialogTitle("Open File"); //设置打开文件对话框的标题

try {

flag = jFileChooser.showOpenDialog(jframe);

} // 这里显示打开文件的对话框,flag会被赋值为0

catch (HeadlessException head) {

System.out.println("Open File Dialog ERROR!");

}

// 如果按下确定按钮,则获得该文件。

if (flag == JFileChooser.APPROVE_OPTION) // flag值为0,选择打开 值也为0

{

file = jFileChooser.getSelectedFile(); // 获得该文件

int scores = 0;

try {

FileInputStream fis = new FileInputStream(file);

scores = fis.read();

} catch (Exception e) {

}

System.out.println("打开的文件为:" + file.getName());

System.out.println("你的分数为:" + scores);

}

}

private void saveFile() // 保存文件

{

String fileName;

// jFileChooser.setDialogTitle("Save File"); //设置保存文件对话框的标题

try {

flag = jFileChooser.showSaveDialog(jframe);

} // 这里将显示保存文件的对话框

catch (HeadlessException he) {

System.out.println("Save File Dialog ERROR!");

}

// 如果按下确定按钮,则获得该文件。

if (flag == JFileChooser.APPROVE_OPTION) // flag的值为0,approve option的值也为0

{

file = jFileChooser.getSelectedFile();// 获得你输入要保存的文件

fileName = jFileChooser.getName(file);// 获得文件名和要保存的路径

String path = file.getAbsolutePath(); // 得到要保存文件的路径

String s1 = path.replace('\\', '/'); // 最终的输出路径,目的是把path中的'\'变成'/'

int a = s1.length();

flag1 = true;

// 创建文件输出流

if (flag1 == true) {

try {

FileOutputStream fos = new FileOutputStream(s1);

int message = 97;

fos.write(message);

flag1 = false;

} catch (Exception e) {

}

}

}

}

}

694748ed64b9390909c0d88230893790.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值