zoukankan      html  css  js  c++  java
  • java 写文本文件

    code 1:将特定String写入特定文件,不覆盖。

    import java.io.*;
    import java.util.*;
    
    public class OutputLog {
        public static void main(String[] args) {
            outPutLogToDeaktop("log.txt", "11111111111");
            outPutLogToDeaktop("log.txt", "222222");
        }
            
        
        public static void outPutLogToDeaktop(String fileName, String info) {
            File out_file = new File("/home/wangyong/Desktop/" + fileName);
            try {
                FileWriter fw = new FileWriter(out_file, out_file.exists());
                fw.write( (new Date()).toString() + " : " + info + "
    " );
                fw.close();
            } catch (IOException e) {
                System.out.println("FileWriter IOException!");
                e.printStackTrace();
            }        
        }
    }

    FileWriter fw = new FileWriter(out_file, out_file.exists()); 这一句,如果out_file.exists()为真,则以Append(在文本最后添加而不覆盖)方式写新内容,如果out_file.exists()为假,创建文件并写入。

    输出结果:

    Fri Jan 03 19:07:52 CST 2014 : 11111111111
    Fri Jan 03 19:07:52 CST 2014 : 222222
    Fri Jan 03 19:07:53 CST 2014 : 11111111111
    Fri Jan 03 19:07:53 CST 2014 : 222222

    code 2: 直接将控制台的输出写入文件

    import java.io.*;
    import java.util.*;
    
    public class OutputLog {
        public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("yyyy.txt");  
        System.setOut(new PrintStream(fos));  
        System.out.println("frfr");
        }
    }

    code 3: 一行一行读文件

    String s;
    FileReader fr=new FileReader("public.txt");
    BufferedReader br=new BufferedReader(fr);
    while((s=br.readLine())!=null)
        System.out.println(s);
    br.close();
  • 相关阅读:
    BOJ 85 Three Points On A Line
    BOJ 84 Single Number
    BOJ 83 A + B Problem
    【转载】运算符优先级
    匹配体重和为特定值的人,两两成对
    The Brand New Beginning!
    【失败】制作CentOS镜像
    【制作镜像】安装VMwareTool
    部署巡检脚本
    windows server 2008镜像重启后密码变为默认密码的问题的解决方案
  • 原文地址:https://www.cnblogs.com/duanguyuan/p/3504187.html
Copyright © 2011-2022 走看看