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();
  • 相关阅读:
    一个简单的rest_framework demo
    linux 文本编辑 软件管理
    linux 底层 基础命令 路径信息
    linux 安装 配置网络 备份 快照
    简单学习Python之路1
    站点的rel="alternate"属性
    mongoose的save无效的问题
    css3动画:transition和animation
    《http权威指南》读书笔记18
    《http权威指南》读书笔记17
  • 原文地址:https://www.cnblogs.com/duanguyuan/p/3504187.html
Copyright © 2011-2022 走看看