最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中write(char[] ch,int off,int length),flush()和close()方法为抽象方法,Reader中read(char[] ch,int off,int length)和close()方法是抽象方法。子类应该分别实现他们。
当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStreamReader和BufferedReader。其中最重要的类是InputStreamReader,它是字节转换为字符的桥梁。你可以在构造器重指定编码的方式,如果不指定的话将采用底层操作系统的默认编码方式,例如GBK等。当使用FileReader读取文件的时候。
FileReader fr = new FileReader("ming.txt");
int ch = 0;
while((ch = fr.read())!=-1 )
{
System.out.print((char)ch);
}
其中read()方法返回的是读取得下个字符。当然你也可以使用read(char[] ch,int off,int length)这和处理二进制文件的时候类似,不多说了。如果使用InputStreamReader来读取文件的时候
while((ch = isr.read())!=-1)
{
System.out.print((char)ch);
}
这和FileReader并没有什么区别,事实上在FileReader中的方法都是从InputStreamReader中继承过来的。read()方法是比较好费时间的,如果为了提高效率我们可以使用BufferedReader对Reader进行包装,这样可以提高读取得速度,我们可以一行一行的读取文本,使用readLine()方法。
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));
String data = null;
while((data = br.readLine())!=null)
{
System.out.println(data);
}
当你明白了如何用Reader来读取文本文件的时候那么用Writer写文件同样非常简单。有一点需要注意,当你写文件的时候,为了提高效率,写入的数据会先放入缓冲区,然后写入文件。因此有时候你需要主动调用flush()方法。与上面对应的写文件的方法为:
FileWriter fw = new FileWriter("hello.txt");
String s = "hello world";
fw.write(s,0,s.length());
fw.flush();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2.txt"));
osw.write(s,0,s.length());
osw.flush();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true);
pw.println(s);
不要忘记用完后关闭流!下面是个小例子,帮助新手理解。其实有的时候java的IO系统是需要我们多记记的,不然哪天就生疏了。
hello world i like java language
import java.io.*;
public class TestFile2
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("ming.txt");
char[] buffer = new char[1024];
int ch = 0;
while((ch = fr.read())!=-1 )
{
System.out.print((char)ch);
}
InputStreamReader isr = new InputStreamReader(new FileInputStream("ming.txt"));
while((ch = isr.read())!=-1)
{
System.out.print((char)ch);
}
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));
String data = null;
while((data = br.readLine())!=null)
{
System.out.println(data);
}
FileWriter fw = new FileWriter("hello.txt");
String s = "hello world";
fw.write(s,0,s.length());
fw.flush();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2.txt"));
osw.write(s,0,s.length());
osw.flush();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true);
pw.println(s);
fr.close();
isr.close();
br.close();
fw.close();
osw.close();
pw.close();
}
}
import java.io.*;
import java.util.*;
public class test{
public static void main(String[] args) {
String ss="1$2$3$";
StringTokenizer token = new StringTokenizer(ss, "$", false);
while(token.hasMoreElements()){
String sToken = (token.nextElement()).toString();
System.err.println(sToken);
}
}
}
import java.io.*;
import java.util.*;
import javax.swing.*;
public class ExchangeFile {
//private String fileName;
public void transferToTxtFile(String fileName, ArrayList applyBean) throws
IOException {
char token = '$';
StringBuffer sb = new StringBuffer();
UserInfo[] userInfoArray = new UserInfo[applyBean.size()];
String saveFileName = "d:\\" + fileName;
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(saveFileName)));
for (int i = 0; i < applyBean.size(); i++) {
userInfoArray[i] = (UserInfo) applyBean.get(i);
sb.append(userInfoArray[i].getUserName());
sb.append(token);
sb.append(userInfoArray[i].getUserAge());
sb.append(token);
writer.write(sb.toString());
writer.newLine(); //line separator as defined by the system property line.separator.
writer.flush();
sb.delete(0, sb.length());
}
writer.close();
}
public ArrayList getFromTxtFile(String fileName) throws IOException {
String readFileName = "d:\\" + fileName;
BufferedReader reader = new BufferedReader(new InputStreamReader(new
FileInputStream(readFileName)));
String str = null;
StringTokenizer token;
ArrayList sToken = new ArrayList();
ArrayList aL = new ArrayList();
int i = 0;
while ((str = reader.readLine()) != null) {
token = new StringTokenizer(str, "$", false);
while (token.hasMoreTokens()) {
String tempToken = (token.nextToken()).toString();
sToken.add(tempToken);
}
UserInfo user = new UserInfo();
user.setUserName((String) sToken.get(0));
user.setUserAge((String) sToken.get(1));
sToken.clear();
aL.add(user);
i++;
}
reader.close();
return aL;
}
public static void main(String[] args) throws IOException {
// JOptionPane.showInputDialog("test 'transferToTxtFile' input 1 please;test getFromTxtFile input 2 please" );
UserInfo user1 = new UserInfo();
user1.setUserName("ytfei");
user1.setUserAge("21");
UserInfo user2 = new UserInfo();
user2.setUserName("feixiang");
user2.setUserAge("22");
ArrayList aL = new ArrayList();
aL.add(user1);
aL.add(user2);
ExchangeFile efile = new ExchangeFile();
efile.transferToTxtFile("1.txt", aL);
aL.clear();
/*
ExchangeFile efile = new ExchangeFile();
ArrayList aL = efile.getFromTxtFile("1.txt");
System.out.println(((UserInfo)aL.get(0)).getUserName());
System.out.println(((UserInfo)aL.get(0)).getUserAge());
System.out.println(((UserInfo)aL.get(1)).getUserName());
System.out.println(((UserInfo)aL.get(1)).getUserAge());
*/
}
}
class UserInfo {
private String userName;
private String userAge;
public void setUserName(String username) {
this.userName = username;
}
public String getUserName() {
return this.userName;
}
public void setUserAge(String age) {
this.userAge = age;
}
public String getUserAge() {
return this.userAge;
}
}