当前位置: 移动技术网 > IT编程>开发语言>Java > java的io操作(将字符串写入到txt文件中)

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

复制代码 代码如下:

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);
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网