如果我2.txt中有abc,以下是我的源代码:
FileOutputStream fo=new FileOutputStream("2.txt");
FileInputStream fi=new FileInputStream("2.txt");
byte[] b=new byte[10];
int i=fis.read(b);
System.out.println(i);会发现输出的是-1,而2.txt文件中的内容变为空....很费解,想过很多解释,比如输出流在关闭的时候,向文件中输出空串等但是都觉得不太对。。希望大家给个建议谢谢JavaJava ioFileOutputStreamFileInputStream
FileOutputStream fo=new FileOutputStream("2.txt");
FileInputStream fi=new FileInputStream("2.txt");
byte[] b=new byte[10];
int i=fis.read(b);
System.out.println(i);会发现输出的是-1,而2.txt文件中的内容变为空....很费解,想过很多解释,比如输出流在关闭的时候,向文件中输出空串等但是都觉得不太对。。希望大家给个建议谢谢JavaJava ioFileOutputStreamFileInputStream
FileOutputStream fo=new FileOutputStream("c:\\2.txt",true);
后边有参数是表示是不是追加的方式,否则就是重写的方式,有了这个参数就知道为什么了.
你的代码里没有后边的fi结果也一样,就是说:
FileOutputStream fo=new FileOutputStream("2.txt");
fo.close();
这个文件的内容就没有了
按照sdk的api 文档FileInputStream 的 read(byte[])
的返回值描述Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.返回共读了多少个字节到缓冲中,如果到达文件尾啥都没读到就返回-1
说明: stream 已经读到文件尾了,而且没读到任何东西。结论:空文件。
在看FileOutputStream 的API构造器描述public FileOutputStream(String name)
throws FileNotFoundExceptionCreates a file output stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.First, if there is a security manager, its checkWrite method is called with name as its argument.If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.文档并没有明说,是否覆盖,只是说如果是有安全管理,或者是已经存在同名的文件夹将抛出异常。
但是,后面有一个 FileOutputStream(string name ,boolean append)
如果append 就在文件后面追加。结论,调用FileOuputStream("2.txt"); 将原来文件覆盖了。一个新文件产生了。
this(name != null ? new File(name) : null, false);
}发现其调用了另一个构造 (构造里面调用构造...)另一个构造是
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();
}
this.fd = new FileDescriptor();
this.append = append; fd.incrementAndGetUseCount();
open(name, append);
}相当于第二个参数传入的是false最后调用了open(name,append)
/**
* Opens a file, with the specified name, for overwriting or appending.
* @param name name of file to be opened
* @param append whether the file is to be opened in append mode
*/
private native void open(String name, boolean append)
throws FileNotFoundException;这是一个私有的native 函数 即所谓的JNI。说明这里调用了C\C++的库函数
这个且不管。上面的描述说,覆盖或者追加。就看是否有这个trueFileOutputStream(String) 本质传入的是false,所以是覆盖了(不过API描述的也太不具体了)