JAVA初学者,想要实现如题目一样的需求,写一天了,网上能查到的方法都试了个遍,bufferedreader,filereader,fileinputstream都写了还是打不开文件,我在open那个地方的代码是有问题的,原本想着将字节数组转为string类型,后来发现编译不通过。代码不全,new和save都已实现就没有粘贴过来了,希望大家能给我改改,感谢!
package Txt;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class TxtS {
private File f1;
private TextArea Tx;
TxtS() {
init();
}
public void init() {
Frame f = new Frame("TXT tool");
Tx = new TextArea();
//Panel p1 = new Panel();
FileDialog openDia = new FileDialog(f, "选择需要加载的文件", FileDialog.LOAD);
FileDialog saveDia = new FileDialog(f, "选择你要保存的位置", FileDialog.SAVE);
Button b3 = new Button("New");
Button b4 = new Button("Open");
Button b5 = new Button("Save");
// Button b6 = new Button("A"); 暂缓处理改变字体
//p1.setBounds(0, 0, 300, 800);
f.setBounds(300, 100, 1200, 800);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
Tx.setBounds(300, 0, 900, 800);
f.setVisible(true);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(Tx);
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openDia.setVisible(true);
String dirPath = saveDia.getDirectory();
String filename = saveDia.getFile();
if (dirPath == null || filename == null)
return;
Tx.setText(" "); // 清空文本
//File f1 = new File(dirPath, filename);
try {
// BufferedReader bufr = new BufferedReader(new FileReader(f1));
// String line;
// while ((line = bufr.readLine()) != null) {
// Tx.append(line+ "\r\n");
// Tx.setText(line);
//}
// bufr.close();
String path = dirPath+filename;
//FileReader reader = new FileReader(path) ;
FileInputStream fis = new FileInputStream(path);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
//StringBuffer result = new StringBuffer();
int len=0;
String[] s= new String(bytes);
while((len=fis.read(bytes))!=-1){
Tx.setText(s);
}
// Tx.append(bytes);
// }
// fis.close();
//Tx.setText(result.toString());
System.out.println("读档成功!");
} catch (IOException e1) {
throw new RuntimeException("打开失败!");
}
// catch(FileNotFoundException e1){
// e1.printStackTrace();
// }
}
});
// ----------------------------------------------------
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new TxtS();
}
}
path输出看下是不是地址不对。