读文件: 先得到文件地址如:"E:\\old.txt",这里绝对路径时有'\',要用双的;
然后得到文件句柄:File file = new File("filePath");
判断文件是否存在 if(file.isFile() && file.exists());
获得一个输入流,可以读文件:InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
//endcoding 是一个String类型字符串,编码格式
获得一个读入缓冲BufferedReader br = new BufferedReader(read);
然后开始读。
写文件:
获得文件句柄:File file = new File("E:\\new.txt");
得到输出流:OutputStream os = new FileOutputStream(file);
得到一个打印流:PrintStream ps = new PrintStream(os);
写:ps.print(String s);
注意:写文件时,经常不能写出换行
因为写在s后加换行是s.append("\r\n");
源码:
public class CMain {
public static void main(String[] args) {
String filePath = "E:\\old.txt";
StringBuffer buffer = new StringBuffer("Only a test\n");
File file = new File("E:\\new.txt");
try {
OutputStream os = new FileOutputStream(file);
readTxtFile(filePath, os);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("over!!!!!!");
}
//读文件
public static void readTxtFile(String filePath, OutputStream os) {
try {
String encoding = "GBK";
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
StringBuffer sb = new StringBuffer(lineTxt);
sb.append("\r\n");
writeFromBuffer(sb, os);
// writeFromBuffer("\r\n", os);
}
read.close();
} else {
System.out.println("找不到指定文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
//写入
public static void writeFromBuffer(StringBuffer buffer, OutputStream os) {
PrintStream ps = new PrintStream(os);
ps.print(buffer.toString());
}
public static void writeFromBuffer(String string, OutputStream os) {
StringBuffer sb = new StringBuffer(string);
writeFromBuffer(sb, os);
}
}