编写java 程序 打开TXT文件
发布网友
发布时间:2022-05-05 06:07
我来回答
共2个回答
热心网友
时间:2023-10-12 06:18
你的txt文件名字叫00.txt,放在c盘根目录。内容写成:
a
b
c
d
e
或者:abcde。我给你写了个,运行成功了!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class findFile {
public String loadAFileToStringDE(String path) throws IOException {
ArrayList Arry = new ArrayList();
File f = new File(path);
BufferedReader br = null;
String ret = null;
System.out.println(f);
try {
br = new BufferedReader(new FileReader(f));
String line = null;
while ((line = br.readLine()) != null) {
Arry.add(line);
}
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
}
}
}
String temp = (String)Arry.get(Arry.size()-1);
System.out.println("最后一个字母:"+temp.substring(temp.length()-1,temp.length()));
return (String)Arry.get(Arry.size()-1);
}
public static void main(String[] args) {
findFile files= new findFile();
try{
System.out.println("最后一行"+files.loadAFileToStringDE("c:/00.txt"));
}catch(IOException io){}
}
}
结果:
c:\00.txt
最后一个字母:e
最后一行e
热心网友
时间:2023-10-12 06:19
关键代码:
FileInputStream filein=new FileInputStream("C:\\xx.txt");//文件路径
byte[] b = new byte[filein.available()];
filein.read(b);
String text = new String(b);
String content = "第5个字符是:" + text.charAt(4) + "\n文件内容是:\n"+text;
下面是一个带文件浏览框的代码,用于读文本文件,你运行下就知道了:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class ReadTxtTest {
JFrame frame = new JFrame("读取文件");
JTextArea ta = new JTextArea();
public ReadTxtTest() {
JButton b1 = new JButton("请选择文件");
b1.addActionListener(new al());
Container cp = frame.getContentPane();
cp.setLayout(new BorderLayout());
cp.add(b1, BorderLayout.NORTH);
cp.add(ta, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
class al implements ActionListener {
public void actionPerformed(ActionEvent e){
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(null);
int value=0;
if(value==JFileChooser.APPROVE_OPTION){
String filename=null;
String filedirectory=null;
String file_and_directoryname=null;
if(fc.getSelectedFile()==null)
return;
filename=fc.getSelectedFile().getName();
filedirectory=fc.getCurrentDirectory().toString();
file_and_directoryname=filedirectory+"/"+filename;
try {
FileInputStream filein=new FileInputStream(file_and_directoryname);
byte[] b = new byte[filein.available()];
filein.read(b);
String text = new String(b);
ta.setText("第5个字符是:" + text.charAt(4) + "\n文件内容是:\n"+text);
filein.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} }
public static void main(String[] args) {
new ReadTxtTest();
}
}