java读写文件

import java.io.*;

public class Demo {
public static void main(String[] args) {
try {
// 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw
String pathname = "F:/input.txt";
InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(pathname))); // 建立一个输入流对象reader
BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言
/* 写入Txt文件 */
File writename = new File("F:/output.txt");
if (writename.exists()) {
writename.delete();
}
writename.createNewFile(); // 创建新文件
BufferedWriter out = new BufferedWriter(new FileWriter(writename));
String line = null;
while ((line = br.readLine()) != null) {
out.write(line + "\r\n"); // \r\n即为换行
}
out.flush(); // 把缓存区内容压入文件
out.close(); // 最后记得关闭文件
br.close();
reader.close();

} catch (Exception e) {
e.printStackTrace();
}

}
}

//同过判断文件的结尾来读取文件   
import java.io.File;   
import java.io.InputStream;   
import java.io.FileInputStream;   
public class InputStreamDemo02   
{   
    public static void main(String args[]) throws Exception{   
        File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");   
        InputStream in = new FileInputStream(f);   
        byte b[] = new byte[1024];   
        int len = 0;   
        int temp=0;          //所有读取的内容都使用temp接收   
        while((temp=in.read())!=-1){    //当没有读取完时,继续读取   
            b[len]=(byte)temp;   
            len++;   
        }   
        in.close();   
        System.out.println(new String(b,0,len));   
    }   

posted on 2018-11-05 10:29  cxhfuujust  阅读(125)  评论(0编辑  收藏  举报

导航