在读入的二进制文件中可能某个字节的值可能是-1。它是c/c++中的EOF的值,在java中也是标示文件的末尾。
在c/c++中可以用feof()函数检测是否到了文件的末尾,但是在java的i/o库里面并没有相关的对象或者函数,对读取二进制文件,并且检测某个值为-1的字节是文件末尾还是某个字节,而是强硬的说到了文件末尾。
具体说,下面是我用c实现的:在java中该怎么做??#include <cstdio>
#include <iostream>
using namespace std;int main(){
FILE* fp;
FILE* fp2;
fp=fopen("123.wav","rb");
fp2=fopen("123.txt","wb");
char t;
long jj=0;
while(!feof(fp)){
t=fgetc(fp);
jj++;
printf("%d:%c\n",t,t);
fprintf(fp2,"%d:%c",t,t);
fprintf(fp2,"\n");
}
cout<<jj;
fclose(fp);
fclose(fp2);
}
在c/c++中可以用feof()函数检测是否到了文件的末尾,但是在java的i/o库里面并没有相关的对象或者函数,对读取二进制文件,并且检测某个值为-1的字节是文件末尾还是某个字节,而是强硬的说到了文件末尾。
具体说,下面是我用c实现的:在java中该怎么做??#include <cstdio>
#include <iostream>
using namespace std;int main(){
FILE* fp;
FILE* fp2;
fp=fopen("123.wav","rb");
fp2=fopen("123.txt","wb");
char t;
long jj=0;
while(!feof(fp)){
t=fgetc(fp);
jj++;
printf("%d:%c\n",t,t);
fprintf(fp2,"%d:%c",t,t);
fprintf(fp2,"\n");
}
cout<<jj;
fclose(fp);
fclose(fp2);
}
FileInputStream fis=new FileInputStream("路径+文件名");
int index=fis.avilable();在这里 变量index就是该文件的字节个数。
byte[] buffer=new byte[index];
fis.read(buffer);这样就把文件内容存到了字节数组里面了;
public abstract int read()
throws IOExceptionReads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
A subclass must provide an implementation of this method.
Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException - if an I/O error occurs.-------------------------------
所以不存在“在读入的二进制文件中可能某个字节的值可能是-1。”的问题,是0-255
读文件的话while(fileinputstream.read()!=-1){...}即可楼上的
byte[] buffer=new byte[index];
fis.read(buffer);
对于小文件处理是没问题,大文件肯定是不行的
fp2=fopen("123.txt","wb");
char t;
long jj=0;
while(!feof(fp)){
t=fgetc(fp);
jj++;
printf("%d:%c\n",t,t);
fprintf(fp2,"%d:%c",t,t);
fprintf(fp2,"\n");
你这个C代码明显有问题,用二进制打开,却用文本方式读和写.最好匹配.
wb -- fread, fwrite
我是读入一个字节
在把它按照int和char的形式显示
写不知道有没有问题:但是按找意愿工作了 :)
我觉得你的理由比较足,但是我实际的代码中是遇到这样的问题了
是用DataInputStream 的 readByte()方法读入的
其他对象我也试过read()的方法不知道是什么情况
,在试试
2楼说的方法还没有试
我是读入一个字节
在把它按照int和char的形式显示
写不知道有没有问题:但是按找意愿工作了 :)这是对 cenlmmx(学海无涯苦作舟) 说的