文档详情

java读取文件方法大全 .doc

发布:2018-03-23约7.77万字共51页下载文档
文本预览下载声明
一、多种方式读文件内容。 1、按字节读取文件内容 2、按字符读取文件内容 3、按行读取文件内容 4、随机读取文件内容 Java代码 1.import java.io.BufferedReader; 2.import java.io.File; 3.import java.io.FileInputStream; 4.import java.io.FileReader; 5.import java.io.IOException; 6.import java.io.InputStream; 7.import java.io.InputStreamReader; 8.import java.io.RandomAccessFile; 9.import java.io.Reader; 10. 11.public class ReadFromFile { 12. /** 13. * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 14. * 15. * @param fileName 16. * 文件的名 17. */ 18. public static void readFileByBytes(String fileName) { 19. File file = new File(fileName); 20. InputStream in = null; 21. try { 22. System.out.println(以字节为单位读取文件内容,一次读一个字节:); 23. // 一次读一个字节 24. in = new FileInputStream(file); 25. int tempbyte; 26. while ((tempbyte = in.read()) != -1) { 27. System.out.write(tempbyte); 28. } 29. in.close(); 30. } catch (IOException e) { 31. e.printStackTrace(); 32. return; 33. } 34. try { 35. System.out.println(以字节为单位读取文件内容,一次读多个字节:); 36. // 一次读多个字节 37. byte[] tempbytes = new byte[100]; 38. int byteread = 0; 39. in = new FileInputStream(fileName); 40. ReadFromFile.showAvailableBytes(in); 41. // 读入多个字节到字节数组中,byteread为一次读入的字节数 42. while ((byteread = in.read(tempbytes)) != -1) { 43. System.out.write(tempbytes, 0, byteread); 44. } 45. } catch (Exception e1) { 46. e1.printStackTrace(); 47. } finally { 48. if (in != null) { 49. try { 50. in.close(); 51. } catch (IOException e1) { 52. } 53. } 54. }
显示全部
相似文档