文件输出流FileOutputStream练习

文件输出流FileOutputStream,课后练习的实现。要求:1.实现使用write(char[] cbuf)方法把中英文字符分别写入File。
2.实现使用write(int c)方法把中英文字符分别写入File。
实现结果:1.用write(char[] cbuf)方法是因为把字符串转换成了byte数组,故中英文字符都能写入,且不是乱码。
2.用write(int c)方法进行写入是是一个字节一个字节写入的,故写入时只有英文字符和数字字符是正常显式,中文字符是乱码,因为一个汉字是两个字节。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 1.实现使用write(char[] cbuf)方法把中英文字符分别写入File。
* 2.实现使用write(int c)方法把中英文字符分别写入File。
* @author Administrator
*
*/ class Outputwriteinti {

public static void main(String[] args) {
//用作使用write(char[] cbuf)方法时使用 写入英文字符
String s="asfgfhgjlkjjlqee";
//用作使用write(char[] cbuf)方法时使用 写入中文字符
String ss="今天天气好晴朗,处处好风光。";
//用作使用write(int c)方法时使用
String s1="asfgfhgjlkjjlqee-----今天天气好晴朗,处处好风光。------";

//创建输出流对象
FileOutputStream fx=null;
FileOutputStream fy=null;

//创建文件
File fa=new File("F:\\sun\\x.txt");
File fb=new File("F:\\sun\\y.txt");

// 文件如果不存在就创建
if(!fa.exists()){
try {
fa.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(!fb.exists()){
try {
fb.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

try {
//给输出流对象赋值
fx=new FileOutputStream(fa);
fy=new FileOutputStream(fb);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//用write(int c)方法 每次写入单个字符。
for(int i=0;i<s1.length();i++){
try {
fx.write(s1.charAt(i));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//字符串变字符数组
byte [] b=s.getBytes();
byte [] bb=ss.getBytes();

try {
//将数据写入输出流对象
fx.write(b);
fy.write(b, 0, s.length()/2);
fx.write(bb);
fy.write(bb, 0, 12);//一个汉字是两个字节

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

finally {
//文件不为空的时候关闭文件(因为可能会创建失败 创建失败的话就为空 就不用关)
if(fx!=null){
try {
fx.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fy!=null){
try {
fy.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
  }
}


猜你喜欢

转载自sunflower-13.iteye.com/blog/2317262
今日推荐