
最基本的实际是(3),12最后都会转化成3的格式。但3很少有人用。
看源代码可知:三者本质没有任何区别。
public FileInputStream(String name) throws FileNotFoundException {
this(name != null new File(name) : null);
}
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null filegetPath() : null);
SecurityManager security = SystemgetSecurityManager();
if (security != null) {
securitycheckRead(name);
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
fdincrementAndGetUseCount();
open(name);
}
public FileInputStream(FileDescriptor fdObj) {
SecurityManager security = SystemgetSecurityManager();
if (fdObj == null) {
throw new NullPointerException();
}
if (security != null) {
securitycheckRead(fdObj);
}
fd = fdObj;
fdincrementAndGetUseCount();
}
目的就是构造函数的重载,方便开发而已。。。
Java读取二进制文件,以字节为单位进行读取,还可读取、音乐文件、视频文件等,
在Java中,提供了四种类来对文件进行 *** 作,分别是InputStream OutputStream Reader Writer ,前两种是对字节流的 *** 作,后两种则是对字符流的 *** 作。
示例代码如下:
public static void readFileByBytes(String fileName){
File file = new File(fileName);
InputStream in = null;
try {
Systemoutprintln("一次读一个");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = inread()) != -1) {
Systemoutwrite(tempbyte);
}
inclose();
} catch (IOException e) {
eprintStackTrace();
return;
}
关键是fisread(b,0,blength)这句,如果你的总体的内容长度不能整除blength那么它会把一些空字符串塞满这次b。导致b读取的内容就不对了。
因为FileInputStream这个类的read方法返回的是一个整型值。不好 *** 作
建议你这么写:
BufferedReader br = new BufferedReader(new FileReader("testtxt"));
String xml = "";
StringBuilder total = new StringBuilder("");
byte[] b = new byte[1024];
while ((xml = brreadLine())!=null) {
totalappend(xml);
}
while(isread()!=-1){
b[i]=(byte) isread();
i++;
}
这里是错的,当判断isread() != -1的时候这个字节就已经被读取了,于是b[i] = (byte) isread();这里读取的就是后面一个字节,自然会乱码。解决方法如下:
byte c = (byte)isread();while(c != -1){
b[i] = c
i++;
c = (byte)isread();
}
还有一种更方便的:
byte[] b = new byte[isavailable()];isread(b);
以上就是关于java 中 FileInputStream(new File("Text.txt")) 和 FileInputStream(“Text.txt")全部的内容,包括:java 中 FileInputStream(new File("Text.txt")) 和 FileInputStream(“Text.txt")、java怎么实现读取一个文件,拿到二进制流、java使用byte数组,通过FileInputStream读取文件时出现的bug等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)