天天看点

[转]java将字符串写入文件中

java代码  

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("http://www.docin.com/p-315288370.html");// 往文件里写入字符串  

            ps.append("http://www.docin.com/p-315288370.html");// 在已有的基础上添加字符串  

        } catch (filenotfoundexception e) {  

            // todo auto-generated catch block  

            e.printstacktrace();  

        }  

    }  

    public void writestringtofile2(string filepath) {  

            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) {  

    public void writestringtofile3(string filepath) {  

            printwriter pw = new printwriter(new filewriter(filepath));  

            pw.println("abc ");  

            pw.println("def ");  

            pw.println("hef ");  

            pw.close();  

        } catch (ioexception e) {  

    public void writestringtofile4(string filepath) {  

            randomaccessfile rf = new randomaccessfile(filepath, "rw");  

            rf.writebytes("op\r\n");  

            rf.writebytes("app\r\n");  

            rf.writebytes("hijklllll");  

            rf.close();  

    public void writestringtofile5(string filepath) {  

            fileoutputstream fos = new fileoutputstream(filepath);  

            string s = "http://www.docin.com/p-315288370.html";  

            fos.write(s.getbytes());  

            fos.close();  

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

}