BufferedOutputStream bs = null;
FileOutputStream fos = null;
try{
fos = new FileOutputStream(fileName);
bs = new BufferedOutputStream(fos);
//fos.write(outputContent.getBytes());
bs.write(outputContent.getBytes(),0,outputContent.getBytes().length);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}我用被注释掉的fos.write写文件时,可以写到文件中,可我用bs.write写文件时,就写不进去,写的内容是空的.请问一下,这是怎么回事?谢谢大家了.以下是源文件:public class TestByteStream {
public static void main(String[] args) {
//the content that will be write in a file
String outputContent = "these word outputed by byte stream";
//set file path
String filePath = "TestByteStream.txt";
File fileName = new File(filePath);
try{
if(!fileName.exists()){
fileName.createNewFile();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
//output some charactors by byte stream
BufferedOutputStream bs = null;
FileOutputStream fos = null;
try{
fos = new FileOutputStream(fileName);
bs = new BufferedOutputStream(fos);
//fos.write(outputContent.getBytes());
bs.write(outputContent.getBytes(),0,outputContent.getBytes().length);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}}///:~
FileOutputStream fos = null;
try{
fos = new FileOutputStream(fileName);
bs = new BufferedOutputStream(fos);
//fos.write(outputContent.getBytes());
bs.write(outputContent.getBytes(),0,outputContent.getBytes().length);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}我用被注释掉的fos.write写文件时,可以写到文件中,可我用bs.write写文件时,就写不进去,写的内容是空的.请问一下,这是怎么回事?谢谢大家了.以下是源文件:public class TestByteStream {
public static void main(String[] args) {
//the content that will be write in a file
String outputContent = "these word outputed by byte stream";
//set file path
String filePath = "TestByteStream.txt";
File fileName = new File(filePath);
try{
if(!fileName.exists()){
fileName.createNewFile();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
//output some charactors by byte stream
BufferedOutputStream bs = null;
FileOutputStream fos = null;
try{
fos = new FileOutputStream(fileName);
bs = new BufferedOutputStream(fos);
//fos.write(outputContent.getBytes());
bs.write(outputContent.getBytes(),0,outputContent.getBytes().length);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}}///:~
在其后要加
bs.flush();才能将缓冲区的内容真正写到磁盘上。
fos = new FileOutputStream(fileName);
bs = new BufferedOutputStream(fos,20);
//fos.write(outputContent.getBytes());
bs.write(outputContent.getBytes(),0,outputContent.getBytes().length);
//bs.flush();这个时候不用flush它也会向磁盘写入数据的,因为达到了它的缓冲区大小,它就会自动的flush了,你把20改为200试试,如果不手动的flush,它就不会写磁盘。