java读取文件方法

一、多种方式读文件内容。
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. public class ReadFromFile { 
  11. public static void readFileByBytes(String fileName) { 
  12. File file = new File(fileName); 
  13. InputStream in = null; 
  14. try { 
  15. System.out.println("以字节为单位读取文件内容,一次读一个字节:"); 
  16. // 一次读一个字节 
  17. in = new FileInputStream(file); 
  18. int tempbyte; 
  19. while ((tempbyte = in.read()) != -1) { 
  20. System.out.write(tempbyte); 
  21. in.close(); 
  22. } catch (IOException e) { 
  23. e.printStackTrace(); 
  24. return; 
  25. try { 
  26. System.out.println("以字节为单位读取文件内容,一次读多个字节:"); 
  27. // 一次读多个字节 
  28. byte[] tempbytes = new byte[100]; 
  29. int byteread = 0; 
  30. in = new FileInputStream(fileName); 
  31. ReadFromFile.showAvailableBytes(in); 
  32. // 读入多个字节到字节数组中,byteread为一次读入的字节数 
  33. while ((byteread = in.read(tempbytes)) != -1) { 
  34. System.out.write(tempbytes, 0, byteread); 
  35. } catch (Exception e1) { 
  36. e1.printStackTrace(); 
  37. } finally { 
  38. if (in != null) { 
  39. try { 
  40. in.close(); 
  41. } catch (IOException e1) { 
  42. public static void readFileByChars(String fileName) { 
  43. File file = new File(fileName); 
  44. Reader reader = null; 
  45. try { 
  46. System.out.println("以字符为单位读取文件内容,一次读一个字节:"); 
  47. // 一次读一个字符 
  48. reader = new InputStreamReader(new FileInputStream(file)); 
  49. int tempchar; 
  50. while ((tempchar = reader.read()) != -1) { 
  51. // 对于windows下,\r\n这两个字符在一起时,表示一个换行。 
  52. // 但如果这两个字符分开显示时,会换两次行。 
  53. // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。 
  54. if (((char) tempchar) != '\r') { 
  55. System.out.print((char) tempchar); 
  56. reader.close(); 
  57. } catch (Exception e) { 
  58. e.printStackTrace(); 
  59. try { 
  60. System.out.println("以字符为单位读取文件内容,一次读多个字节:"); 
  61. // 一次读多个字符 
  62. char[] tempchars = new char[30]; 
  63. int charread = 0; 
  64. reader = new InputStreamReader(new FileInputStream(fileName)); 
  65. // 读入多个字符到字符数组中,charread为一次读取字符数 
  66. while ((charread = reader.read(tempchars)) != -1) { 
  67. // 同样屏蔽掉\r不显示 
  68. if ((charread == tempchars.length) 
  69. && (tempchars[tempchars.length - 1] != '\r')) { 
  70. System.out.print(tempchars); 
  71. } else { 
  72. for (int i = 0; i < charread; i++) { 
  73. if (tempchars[i] == '\r') { 
  74. continue; 
  75. } else { 
  76. System.out.print(tempchars[i]); 
  77. } catch (Exception e1) { 
  78. e1.printStackTrace(); 
  79. } finally { 
  80. if (reader != null) { 
  81. try { 
  82. reader.close(); 
  83. } catch (IOException e1) { 
  84. public static void readFileByLines(String fileName) { 
  85. File file = new File(fileName); 
  86. BufferedReader reader = null; 
  87. try { 
  88. System.out.println("以行为单位读取文件内容,一次读一整行:"); 
  89. reader = new BufferedReader(new FileReader(file)); 
  90. String tempString = null; 
  91. int line = 1; 
  92. // 一次读入一行,直到读入null为文件结束 
  93. while ((tempString = reader.readLine()) != null) { 
  94. // 显示行号 
  95. System.out.println("line " + line + ": " + tempString); 
  96. line++; 
  97. reader.close(); 
  98. } catch (IOException e) { 
  99. e.printStackTrace(); 
  100. } finally { 
  101. if (reader != null) { 
  102. try { 
  103. reader.close(); 
  104. } catch (IOException e1) { 
  105. public static void readFileByRandomAccess(String fileName) { 
  106. RandomAccessFile randomFile = null; 
  107. try { 
  108. System.out.println("随机读取一段文件内容:"); 
  109. // 打开一个随机访问文件流,按只读方式 
  110. randomFile = new RandomAccessFile(fileName, "r"); 
  111. // 文件长度,字节数 
  112. long fileLength = randomFile.length(); 
  113. // 读文件的起始位置 
  114. int beginIndex = (fileLength > 4) ? 4 : 0; 
  115. // 将读文件的开始位置移到beginIndex位置。 
  116. randomFile.seek(beginIndex); 
  117. byte[] bytes = new byte[10]; 
  118. int byteread = 0; 
  119. // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。 
  120. // 将一次读取的字节数赋给byteread 
  121. while ((byteread = randomFile.read(bytes)) != -1) { 
  122. System.out.write(bytes, 0, byteread); 
  123. } catch (IOException e) { 
  124. e.printStackTrace(); 
  125. } finally { 
  126. if (randomFile != null) { 
  127. try { 
  128. randomFile.close(); 
  129. } catch (IOException e1) { 
  130. private static void showAvailableBytes(InputStream in) { 
  131. try { 
  132. System.out.println("当前字节输入流中的字节数为:" + in.available()); 
  133. } catch (IOException e) { 
  134. e.printStackTrace(); 
  135. public static void main(String[] args) { 
  136. String fileName = "C:/temp/newTemp.txt"; 
  137. ReadFromFile.readFileByBytes(fileName); 
  138. ReadFromFile.readFileByChars(fileName); 
  139. ReadFromFile.readFileByLines(fileName); 
  140. ReadFromFile.readFileByRandomAccess(fileName); 
  141. }

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.RandomAccessFile;

import java.io.Reader;

public class ReadFromFile {

public static void readFileByBytes(String fileName) {

File file = new File(fileName);

InputStream in = null;

try {

System.out.println("以字节为单位读取文件内容,一次读一个字节:");

// 一次读一个字节

in = new FileInputStream(file);

int tempbyte;

while ((tempbyte = in.read()) != -1) {

System.out.write(tempbyte);

}

in.close();

} catch (IOException e) {

e.printStackTrace();

return;

}

try {

System.out.println("以字节为单位读取文件内容,一次读多个字节:");

// 一次读多个字节

byte[] tempbytes = new byte[100];

int byteread = 0;

in = new FileInputStream(fileName);

ReadFromFile.showAvailableBytes(in);

// 读入多个字节到字节数组中,byteread为一次读入的字节数

while ((byteread = in.read(tempbytes)) != -1) {

System.out.write(tempbytes, 0, byteread);

}

} catch (Exception e1) {

e1.printStackTrace();

} finally {

if (in != null) {

try {

in.close();

} catch (IOException e1) {

}

}

}

}

public static void readFileByChars(String fileName) {

File file = new File(fileName);

Reader reader = null;

try {

System.out.println("以字符为单位读取文件内容,一次读一个字节:");

// 一次读一个字符

reader = new InputStreamReader(new FileInputStream(file));

int tempchar;

while ((tempchar = reader.read()) != -1) {

// 对于windows下,\r\n这两个字符在一起时,表示一个换行。

// 但如果这两个字符分开显示时,会换两次行。

// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。

if (((char) tempchar) != '\r') {

System.out.print((char) tempchar);

}

}

reader.close();

} catch (Exception e) {

e.printStackTrace();

}

try {

System.out.println("以字符为单位读取文件内容,一次读多个字节:");

// 一次读多个字符

char[] tempchars = new char[30];

int charread = 0;

reader = new InputStreamReader(new FileInputStream(fileName));

// 读入多个字符到字符数组中,charread为一次读取字符数

while ((charread = reader.read(tempchars)) != -1) {

// 同样屏蔽掉\r不显示

if ((charread == tempchars.length)

&& (tempchars[tempchars.length - 1] != '\r')) {

System.out.print(tempchars);

} else {

for (int i = 0; i < charread; i++) {

if (tempchars[i] == '\r') {

continue;

} else {

System.out.print(tempchars[i]);

}

}

}

}

} catch (Exception e1) {

e1.printStackTrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e1) {

}

}

}

}

public static void readFileByLines(String fileName) {

File file = new File(fileName);

BufferedReader reader = null;

try {

System.out.println("以行为单位读取文件内容,一次读一整行:");

reader = new BufferedReader(new FileReader(file));

String tempString = null;

int line = 1;

// 一次读入一行,直到读入null为文件结束

while ((tempString = reader.readLine()) != null) {

// 显示行号

System.out.println("line " + line + ": " + tempString);

line++;

}

reader.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e1) {

}

}

}

}

public static void readFileByRandomAccess(String fileName) {

RandomAccessFile randomFile = null;

try {

System.out.println("随机读取一段文件内容:");

// 打开一个随机访问文件流,按只读方式

randomFile = new RandomAccessFile(fileName, "r");

// 文件长度,字节数

long fileLength = randomFile.length();

// 读文件的起始位置

int beginIndex = (fileLength > 4) ? 4 : 0;

// 将读文件的开始位置移到beginIndex位置。

randomFile.seek(beginIndex);

byte[] bytes = new byte[10];

int byteread = 0;

// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。

// 将一次读取的字节数赋给byteread

while ((byteread = randomFile.read(bytes)) != -1) {

System.out.write(bytes, 0, byteread);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if (randomFile != null) {

try {

randomFile.close();

} catch (IOException e1) {

}

}

}

}

private static void showAvailableBytes(InputStream in) {

try {

System.out.println("当前字节输入流中的字节数为:" + in.available());

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

String fileName = "C:/temp/newTemp.txt";

ReadFromFile.readFileByBytes(fileName);

ReadFromFile.readFileByChars(fileName);

ReadFromFile.readFileByLines(fileName);

ReadFromFile.readFileByRandomAccess(fileName);

}

}

转载于:https://www.cnblogs.com/jjtech/archive/2011/04/17/2019207.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/362063.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何使用github搭建个人博客

1、去github官网注册个人帐号&#xff1a;没有的&#xff1a;猛戳这里去注册&#xff0c;比如我的账户名&#xff1a;wjf444128852&#xff0c;我的已经汉化(可在github里搜索github如何汉化有插件) 2、点击仓库-新建&#xff0c;仓库名字必须是&#xff1a;你的github帐号.git…

Spring Boot和Spring Data REST –通过REST公开存储库

使用Spring Boot和Spring Data REST&#xff0c;通过REST公开Spring Data存储库非常容易。 使用最少的代码&#xff0c;您可以创建遵循HATEOAS原理的JPA实体的REST表示。 我决定重用Spring PetClinic的JPA实体&#xff08;业务层&#xff09;作为本文的基础。 应用基础 PetCli…

记录一次cookie导致登录失败的惨案

现象描述&#xff1a; 前端登录成功后并没有从后端那里拿到登录信息&#xff0c;换句话说登录服务告诉我们登录成功了&#xff0c;但是后端却说我们没有登录成功。 背景&#xff1a; 因为前后端分离&#xff0c;所以前后端项目部署在两个子域名下。 因为要打通登录态&#…

sql中的遇到的有问题的

----题5&#xff1a;求出住在同一城市的顾客对--select city,count(cid) as 顾客的个数 from customers group by city--select --select distinct c1.cname,c2.cname,c1.city from customers c1, customers c2 where c1.cityc2.city and c1.cname<c2.cname select c1.cid,c…

nyoj 55 懒省事的小明 优先队列 multiset 还有暴力

懒省事的小明 时间限制&#xff1a; 3000 ms | 内存限制&#xff1a; 65535 KB难度&#xff1a; 3描述小明很想吃果子&#xff0c;正好果园果子熟了。在果园里&#xff0c;小明已经将所有的果子打了下来&#xff0c;而且按果子的不同种类分成了不同的堆。小明决定把所有的果子…

css3之3d导航

css3的新属性非常不错&#xff0c;目前IE除外其他浏览器都已支持 实现原理:比如元素a在hover时候可以改变元素b的状态。 效果如本农导航&#xff0c;欢迎采用和建议~ a:hover b{ 执行简单动画效果 } HTML <!DOCTYPE html><html lang"en"><head&…

jQuery Ajax – Servlets集成:构建完整的应用程序

网上有很多教程&#xff0c;它们解释了有关使用servlet和JSP页面进行Java Web开发的一些知识&#xff0c;但是&#xff0c;我从来没有找到对于初学者来说足够简洁&#xff0c;简单的教程。 这样的教程应该解释创建一个简单的Web应用程序的整个过程&#xff0c;包括前端&#xf…

ES6中块级作用域下的函数声明

背景 因为ES5的时候没有块级作用域&#xff0c;所以ES5规定不能再if这样的块中声明函数&#xff0c;但是为了兼容各大浏览器并没有严格遵守这条规定。 ES6的时候引入了块级作用域&#xff0c;规定在块级作用域中声明函数就相当于使用let来声明变量一样。但是又因为浏览器端的…

Oracle数据库卸载

Oracle数据库卸载 ORACLE数据库安装起来比较麻烦&#xff0c;卸载也不像微软的产品那样容易。对于ORACLE9的卸载&#xff0c;控制面板里是没有卸载程序的。可以从开始菜单—程序—Oracle Installation Products—Universal Installer 进入安装的界面&#xff0c;界面上有一个…

信息系统开发平台OpenExpressApp - 应用模型ApplicationModel

下图为OpenExpressApp的系统架构图&#xff0c;其中在应用模型是作为一种元数据贯穿于整个架构&#xff0c;应用模型运行在OpenExpressApp框架之上。应用模型是OEA的核心&#xff0c;理解好应用模型才能更好的使用OEA。 应用模型贯穿于整个架构层 模型关注what OEA希望从重复的…

SVN版本控制系统学习(中文配置)

先吐槽下往上搜索的一些SVN下载地址&#xff0c;里面乱七八糟啥都有&#xff0c;下载好后点击安装一不注意啥玩意都安装上了&#xff0c; 什么玩意都有&#xff0c;真心不明白这些推送者是怎么想的。搜集了一个WIN32的百度网盘下载地址&#xff1a; http://pan.baidu.com/s/1…

【译】nginx关于location部分

译&#xff1a; Syntax:location [ | ~ | ~* | ^~ ] uri { ... }location name { ... }Default:—Context:server, location 依据请求的URI进行配置。 在对以"%xx"形式的文本解码&#xff0c;对相对路径".“和”…"的格式化和两个或多个相邻斜杠压缩为单…

自定义汇编程序,Weaver和运行时的可插拔知识

作为贝叶斯工作的一部分&#xff0c;我对Kie进行了很多重构&#xff0c;使其具有清晰的扩展点。 我想确保可以完成贝叶斯系统的所有工作部件&#xff0c;而无需在现有内核中添加任何代码。 因此&#xff0c;现在每种知识类型都可以拥有自己的包&#xff0c;汇编器&#xff0c;…

动态代理

java动态代理 JAVA的动态代理 代理模式 代理模式是常用的java设计模式&#xff0c;他的特征是代理类与委托类有同样的接口&#xff0c;代理类主要负责为委托类预处理消息、过滤消息、把消息转发给委托类&#xff0c;以及事后处理消息等。代理类与委托类之间通常会存在关联关系&…

Kafka学习(一)-------- Quickstart

参考官网&#xff1a;http://kafka.apache.org/quickstart 一、下载Kafka 官网下载地址 http://kafka.apache.org/downloads 截至2019年7月8日 最新版本为 2.3.0 2.12为编译的scala版本 2.3.0为kafka版本 Scala 2.12 - kafka_2.12-2.3.0.tgz (asc, sha512) 解压 > tar -xzf…

关于页面布局间距使用的经验之谈

在页面布局的时候遇到一个问题在此记录。 有如下布局需求。页面上大多数都是这样的&#xff0c;一块一块从上到下排列。 块与块之间的间距需要固定由谁来负责。例如第一个块和第二个块之间的间距&#xff0c;就需要第二个块的margin-top完成&#xff0c;文字和第二个块之间的间…

最简洁的js鼠标拖曳效果【原】

请原谅我是一个标题档&#xff0c;不过还是很简洁的&#xff0c;因为只是初步的实现的拖曳效果<!DOCTYPE html><html><head><meta http-equiv"Content-Type"content"text/html; charsetutf-8"/><meta http-equiv"Content-…

safari 音频播放问题

问题描述&#xff1a; 点击播放音频按钮发现并没有声音&#xff08;并不是自动播放&#xff0c;是有用户行为的&#xff09;。 import React, { useEffect, useState, useRef } from reactfunction comp() {let [paused, setPaused] useState(true)let audioDom useRef(null…

canvas绘制经典折线图(一)

最终效果图如下&#xff1a; 实现步骤如下&#xff1a;注-引用了jQuery HTML代码 <!doctype html><html lang"en"><head><meta charset"UTF-8"><meta name"Generator" content"EditPlus"><meta nam…

如何从Java EE无状态应用程序连接到MongoDB

在本文中&#xff0c;我将介绍如何从无状态Java EE应用程序连接到MongoDB&#xff0c;以利用与MongoDB Java驱动程序提供的数据库的内置连接池。 如果您开发的REST API对MongoDB执行操作&#xff0c;则可能是这种情况。 获取Java MongoDb驱动程序 要将Java连接到MongoDB&#…