欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java的io操作(将字符串写入到txt文件中)

程序员文章站 2024-02-28 14:35:04
复制代码 代码如下:import java.io.file;import java.io.filenotfoundexception;import java.io.file...

复制代码 代码如下:

import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.filewriter;
import java.io.ioexception;
import java.io.printstream;
import java.io.printwriter;
import java.io.randomaccessfile;

public class writestringtotxt {

    public void writestringtofile(string filepath) {
        try {
            file file = new file(filepath);
            printstream ps = new printstream(new fileoutputstream(file));
            ps.println("//www.jb51.net");// 往文件里写入字符串
            ps.append("//www.jb51.net");// 在已有的基础上添加字符串
        } catch (filenotfoundexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }

    public void writestringtofile2(string filepath) {
        try {
            filewriter fw = new filewriter(filepath, true);
            bufferedwriter bw = new bufferedwriter(fw);
            bw.append("在已有的基础上添加字符串");
            bw.write("abc\r\n ");// 往已有的文件上添加字符串
            bw.write("def\r\n ");
            bw.write("hijk ");
            bw.close();
            fw.close();
        } catch (exception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }

    public void writestringtofile3(string filepath) {
        try {
            printwriter pw = new printwriter(new filewriter(filepath));
            pw.println("abc ");
            pw.println("def ");
            pw.println("hef ");
            pw.close();
        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }

    public void writestringtofile4(string filepath) {
        try {
            randomaccessfile rf = new randomaccessfile(filepath, "rw");
            rf.writebytes("op\r\n");
            rf.writebytes("app\r\n");
            rf.writebytes("hijklllll");
            rf.close();
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    public void writestringtofile5(string filepath) {
        try {
            fileoutputstream fos = new fileoutputstream(filepath);
            string s = "//www.jb51.netl";
            fos.write(s.getbytes());
            fos.close();
        } catch (exception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }

    public static void main(string[] args) {
        string filepath = "e:\\link.txt";
        // new writestringtotxt().writestringtofile(filepath);
        // new writestringtotxt().writestringtofile2(filepath);
        // new writestringtotxt().writestringtofile3(filepath);
        // new writestringtotxt().writestringtofile4(filepath);
        new writestringtotxt().writestringtofile5(filepath);
    }
}