java写入文本文件代码
From:
- 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.
FileWriter is meant for writing streams of characters. For
writing streams of raw bytes, consider using a
FileOutputStream.
java.io.PrintWriter
Unlike the 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 .
阅读(3569) | 评论(0) | 转发(0) |