OutputStreamWriter
pw
=
null//定义一个流
pw
=
new
OutputStreamWriter(new
FileOutputStream(“D:/test.txt”),"GBK")//确认流的输出文件和编码格式,此过程创建了“test.txt”实例
pw.write("我是要写入到记事本文件的内容")//将要写入文件的内容,可以多次write
pw.close()//关闭流
解释:文件流用完之后必须及时通过close方法关闭,否则会一直处于打开状态,直至程序停止,增加系统负担。
import java.awt.FlowLayoutimport java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.Calendar
import javax.swing.JButton
import javax.swing.JFileChooser
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JTextField
public class BakTo extends JFrame implements ActionListener {
JLabel l1 = new JLabel("原始文件")
JTextField t1 = new JTextField(40)
JButton b1 = new JButton("选择")
JLabel l2 = new JLabel("保存目录")
JTextField t2 = new JTextField(40)
JButton b2 = new JButton("保存")
JFileChooser j1 = new JFileChooser()
JFileChooser j2 = new JFileChooser()
static File fileFlag = new File("")
public BakTo() {
setBounds(200, 200, 600, 140)
setLayout(new FlowLayout())
add(l1)
add(t1)
add(b1)
add(l2)
add(t2)
add(b2)
b1.addActionListener(this)
b2.addActionListener(this)
setResizable(false)
setVisible(true)
validate()
}
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == b1) {
int n = j1.showOpenDialog(null)
String filename = j1.getSelectedFile().toString()
if (n == JFileChooser.APPROVE_OPTION) {
t1.setText(filename)
fileFlag = new File(filename)
}
}
else if (e.getSource() == b2) {
j2.setCurrentDirectory(fileFlag)// 设置打开对话框的默认路径
j2.setSelectedFile(fileFlag)// 设置选中原来的文件
int n = j2.showSaveDialog(null)
String filename2 = j2.getSelectedFile().toString()
if(filename2.indexOf(".")!=-1){
filename2=filename2.substring(0,filename2.indexOf("."))
}
// 以下两句是获得原文件的扩展名
int flag = t1.getText().lastIndexOf(".")
String kuozhan = t1.getText().substring(flag)
String date = getDate()// 取得当前日期
if (n == JFileChooser.APPROVE_OPTION) {
t2.setText(filename2 +date+ kuozhan)// 把日期和扩展名添加到原来文件的后面
}
int b
char[] t = new char[25]
// 这里我改用了文件流
FileInputStream input = new FileInputStream(t1.getText())
FileOutputStream output = new FileOutputStream(filename2+date
+ kuozhan)// 把扩展名添加到原来文件的后面
int in = input.read()
while (in != -1) {
output.write(in)
in = input.read()
}
input.close()
output.close()
}
} catch (Exception x) {
System.out.println(x)
}
}
public String getDate() {
Calendar rightNow = Calendar.getInstance()
System.out.println(rightNow.toString())
int year = rightNow.YEAR
int date = rightNow.DATE
int month = rightNow.MONTH + 1
String d = year + "年" + month + "月" + date + "日"
return d
}
public static void main(String args[]) {
BakTo c1 = new BakTo()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)