Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2561340
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-12-28 10:44:14

In Java, FileOutputStream is an bytes stream class to handle the raw binary data. To write it, you have to convert the data into bytes, see below example。
以二进制的方式写入数据到文件,完整例子如下:

  1. package org.hnrsc.io;

  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;

  5. //
  6. public class JavaFileIO {

  7.     public static void main(String[] args) {
  8.         try {

  9.           String content = "this is text content..";
  10.           File file = new File("myfile1.txt");
  11.           
  12.           //if file doesn't exists , then create it
  13.           FileOutputStream fop = new FileOutputStream(file);
  14.           //get the content in bytes
  15.           fop.write(content.getBytes());
  16.           fop.flush();
  17.           fop.close();
  18.           
  19.           System.out.println("Done.");
  20.         } catch (IOException e) {
  21.             e.printStackTrace();
  22.         }
  23.     }
  24. }
In Java, BufferedWriter is a character streams class to handle the character data. Unlike bytes stream (convert data into bytes), you can just write the strings, arrays or characters data directly to file.

完整例子如下:

  1. package org.hnrsc.io;

  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;

  6. //
  7. public class JavaFileIO {

  8.     public static void main(String[] args) {
  9.         try {

  10.           String content = "this is text content..";
  11.           File file = new File("myfile2.txt");
  12.           
  13.          if(!file.exists()){
  14.              file.createNewFile();
  15.          }
  16.          FileWriter fw = new FileWriter(file.getName());
  17.          BufferedWriter bw = new BufferedWriter(fw);
  18.          bw.write(content);
  19.          bw.close();
  20.           
  21.           System.out.println("Done.");
  22.         } catch (IOException e) {
  23.             e.printStackTrace();
  24.         }
  25.     }
  26. }

java以追加(append)的方式,写入内容到文件:

FileWritter, a character stream to write characters to file. By default, it will replace all the existing content with new content, however, when you specified a true (boolean) value as the second argument in FileWritter constructor, it will keep the existing content and append the new content in the end of the file.

1. Replace all existing content with new content.

  1. new FileWriter(file);
2. Keep the existing content and append the new content in the end of the file.

  1. new FileWriter(file,true);

阅读(2605) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~