java多种方式读取文件.doc

java多种方式读取文件.doc

ID:61903534

大小:34.50 KB

页数:6页

时间:2021-03-26

java多种方式读取文件.doc_第1页
java多种方式读取文件.doc_第2页
java多种方式读取文件.doc_第3页
java多种方式读取文件.doc_第4页
java多种方式读取文件.doc_第5页
资源描述:

《java多种方式读取文件.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

1、importjava.io.BufferedReader;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.RandomAccessFile;importjava.io.Reader;publicclassRea

2、dFromFile{/***以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。*@paramfileName文件的名*/publicstaticvoidreadFileByBytes(StringfileName){Filefile=newFile(fileName);InputStreamin=null;try{System.out.println("以字节为单位读取文件内容,一次读一个字节:");//一次读一个字节in=newFileInputStream(file);intte

3、mpbyte;while((tempbyte=in.read())!=-1){System.out.write(tempbyte);}in.close();}catch(IOExceptione){e.printStackTrace();return;}try{System.out.println("以字节为单位读取文件内容,一次读多个字节:");//一次读多个字节byte[]tempbytes=newbyte[100];intbyteread=0;in=newFileInputStream(file

4、Name);ReadFromFile.showAvailableBytes(in);//读入多个字节到字节数组中,byteread为一次读入的字节数while((byteread=in.read(tempbytes))!=-1){System.out.write(tempbytes,0,byteread);}}catch(Exceptione1){e1.printStackTrace();}finally{if(in!=null){try{in.close();}catch(IOExceptione1

5、){}}}}/***以字符为单位读取文件,常用于读文本,数字等类型的文件*@paramfileName文件名*/publicstaticvoidreadFileByChars(StringfileName){Filefile=newFile(fileName);Readerreader=null;try{System.out.println("以字符为单位读取文件内容,一次读一个字节:");//一次读一个字符reader=newInputStreamReader(newFileInputStream(

6、file));inttempchar;while((tempchar=reader.read())!=-1){//对于windows下,rn这两个字符在一起时,表示一个换行。//但如果这两个字符分开显示时,会换两次行。//因此,屏蔽掉r,或者屏蔽n。否则,将会多出很多空行。if(((char)tempchar)!='r'){System.out.print((char)tempchar);}}reader.close();}catch(Exceptione){e.printStackTrace();}

7、try{System.out.println("以字符为单位读取文件内容,一次读多个字节:");//一次读多个字符char[]tempchars=newchar[30];intcharread=0;reader=newInputStreamReader(newFileInputStream(fileName));//读入多个字符到字符数组中,charread为一次读取字符数while((charread=reader.read(tempchars))!=-1){//同样屏蔽掉r不显示if((charr

8、ead==tempchars.length)&&(tempchars[tempchars.length-1]!='r')){System.out.print(tempchars);}else{for(inti=0;i

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。