java 写入文件 代码_java写入文本文件代码

java写入文本文件代码

From:http://www.homeandlearn.co.uk/java/write_to_textfile.html

package net.chinaunix.blog.hzm.text;

import java.io.FileWriter;

import java.io.PrintWriter;

import java.io.IOException;

public class WriteFile {

private String path;

private boolean appendToFile = false;

public WriteFile(String filePath){

path = filePath;

}

public WriteFile(String filePath, boolean appendvalue){

path = filePath;

appendToFile = appendvalue;

}

public void writeToFile(String textLine) throws IOException{

FileWriter writer = new FileWriter(path,appendToFile);

PrintWriter printer = new PrintWriter(writer);

printer.printf("%s"+"%n",textLine);

printer.close();

/*The %s between double quotes means a string of characters of any length.

The %n means a newline. So we're telling the printf method to format a      string  of characters and add a newline at the end.

*/

}

}

package net.chinaunix.blog.hzm.text;

import java.io.IOException;

public class FileData {

public static void main(String[] args) throws IOException{

String filePath = "C:/text.txt";

try{

WriteFile writer = new WriteFile(filePath,true);

&n bsp; writer.writeToFile("This is another line..");

}catch(IOException e){

System.out.println(e.getMessage());

}

}

}

java.io.FileWriter

Whether or not a file is available or may be created depends upon the

underlying platform. Some platforms, in particular, allow a file to be opened

for writing by only one FileWriter (or other file-writing object) at a

time. In such situations the constructors in this class will fail if the file

involved is already open.

FileWriteris meant for writing streams of characters. For

writing streams of raw bytes, consider using a

FileOutputStream.

java.io.PrintWriter

Unlike the PrintStream class, if

automatic flushing is enabled it will be done only when one of the

println, printf, or format methods is invoked, rather

than whenever a newline character happens to be output. These methods use the

platform's own notion of line separator rather than the newline character.

Methods in this class never throw I/O exceptions, although some of its

constructors may. The client may inquire as to whether any errors have occurred

by invoking checkError().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值