亲宝软件园·资讯

展开

FileWriter追加文件及改名 java FileWriter 追加文件及文件改名方式

秦学强 人气:1
想了解java FileWriter 追加文件及文件改名方式的相关内容吗,秦学强在本文为您仔细讲解FileWriter追加文件及改名的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,FileWriter,FileWriter追加文件,FileWriter文件改名,下面大家一起来学习吧。

FileWriter 追加文件及文件改名

我就废话不多说了,大家还是直接看代码吧~

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterUtil {
    /**
     * 追加文件:使用FileWriter
     */
    public static void appendMethod(String fileName, String content) {
        try {
            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 修改文件名
     * @param oldFilePath
     * @param newFileName
     */
    public static void reNameLogFile(String oldFilePath,String newFileName){
        File f=new File(oldFilePath);
        String c=f.getParent();
//        File mm=new File(c + File.pathSeparator + newFileName + "_" + CommonUtil.getCurrTimeForString());
        File mm=new File(c + "/" + newFileName + "_" + CommonUtil.getBeforeDateStr());
        if(f.renameTo(mm)){
            System.out.println("修改文件名成功!");
        }else{
            System.out.println("修改文件名失败");
        }
    }
    public static void main(String[] args) {
        String fileName = "/Users/qin/Downloads/callLog.txt";
        String content = "new append!";
        FileWriterUtil.appendMethod(fileName, content);
        FileWriterUtil.appendMethod(fileName, "append end. \n");
        FileWriterUtil.reNameLogFile("/Users/qin/Downloads/callLog.txt","rayda");
    }
}

Java PrintWriter&FileWriter 写入追加到文件

用PrintWriter写入文件

import java.io.IOException;
import java.io.PrintWriter;
public class PrintWriteDemo
{
    public static void main(String[] args) throws IOException
    {
        PrintWriter out = new PrintWriter("01.txt");
        out.print("the quick brown fox");
        out.println(" jumps over the lazy dog.");
        out.write("work is like a capricious lover whose ");
        out.write("incessant demands are resented but who is missed terribly when she is not there\n");
        out.close(); //如果不关闭文件,文件停留在buffer zone, 不会写进"01.txt"中
    }
}

FileWriter只能写入文件,无法往文件中追加内容

用FileWriter写入和追加文件

import java.io.IOException;
import java.io.FileWriter;
public class FileWriterDemo
{
    public static void main(String[] args) throws IOException
    {
        FileWriter out = new FileWriter("02.txt");
        //constructor中添加true,即FileWriter out = new FileWriter("02.txt", true)就是往02.txt中追加文件了
        out.write("work is like a capricious lover whose ");
        out.write("incessant demands are resented but who is missed terribly when she is not there\n");
        out.write(98.7 + "\n");
        out.close(); //很重要,一定记得关闭文件
    }
}

都别忘记 throws IOException

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论