1.纯文本读取
package test.chario;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class Demo01 {
public static void main(String[] args) {
File src = new File("E:/xp/test/a.txt");
Reader reader = null;
try {
reader = new FileReader(src);
char[] flush = new char[1024];
int len = 0;
while (-1 != (len = reader.read(flush))) {
String str = new String(flush, 0, len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("源文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取失败");
} finally {
try {
if (null != reader) {
reader.close();
}
} catch (Exception e2) {
}
}
}
}
2.写出文件
package test.chario;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Demo02 {
public static void main(String[] args) {
File dest = new File("e:/xp/test/char.txt");
Writer wr = null;
try {
wr = new FileWriter(dest);
String msg = "追加.....锄禾日当午\r\n码农真辛苦\r\n一本小破书\r\n一读一上午";
wr.write(msg);
wr.append("倒萨发了看电视剧 ");
wr.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != wr) {
wr.close();
}
} catch (Exception e2) {
}
}
}
}
3.使用字符流实现文件复制
package test.chario;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
public class CopyFileDemo {
public static void main(String[] args) {
File src = new File("E:/xp/test/Demo03.java");
File dest = new File("e:/xp/test/char.txt");
Reader reader = null;
Writer wr = null;
try {
reader = new FileReader(src);
wr = new FileWriter(dest);
char[] flush = new char[1024];
int len = 0;
while (-1 != (len = reader.read(flush))) {
wr.write(flush, 0, len);
}
wr.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("源文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取失败");
} finally {
try {
if (null != wr) {
wr.close();
}
} catch (Exception e2) {
}
try {
if (null != reader) {
reader.close();
}
} catch (Exception e2) {
}
}
}
}