Java实现读取文件

时间:2022-09-18 15:40:11

Java实现读取文件

1、按字节读取文件内容

使用场景
以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

2、按字符读取文件内容

使用场景
以字符为单位读取文件,常用于读文本,数字等类型的文件

3、按行读取文件内容

使用场景
以行为单位读取文件,常用于读面向行的格式化文件

4、随机读取文件内容

使用场景
随机读取文件内容
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);
}
}

Java实现读取文件的更多相关文章

  1. Java中读取文件

    Java中读取文件,去除一些分隔符,保存在多维数组里面 public void readFile(String filePath) { File file=new File(filePath); Ar ...

  2. JAVA本地读取文件,解决中文乱码问题

    JAVA本地读取文件出现中文乱码,查阅一个大神的博客做一下记录 import java.io.BufferedInputStream;import java.io.BufferedReader;imp ...

  3. Java代码读取文件

    用Java代码读取文件时,保持文件本来的格式(主要是保持换行),这点有时候比较重要.用代码实现也相当简单. private static void readFile() { StringBuilder ...

  4. java实现读取文件内容(不同类型)

    在一些项目中大量的数据经常需要从文件中读取,例如xml文件,txt文件,csv文件 1.读取本地的xml文件,需要注意对应的路径 //读取xml文件,xmlFile为读取文件的路径 DocumentB ...

  5. java中读取文件以及向文件中追加数据的总结

    package gys; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; imp ...

  6. Java一次性读取文件的内容

    我们做文本处理的时候的最常用的就是读写文件了,尤其是读取文件,不论是什么文件,我都倾向于一次性将文本的原始内容直接读取到内存中再做处理,当然,这需要你有一台大内存的机器,内存不够者……可以一次读取少部 ...

  7. Java 8 读取文件

    以前的Java版本中读取文件非常繁琐,现在比较简单.使用Java8的Files以及Lambda,几句代码就可以搞定. public static String getXml() { StringBuf ...

  8. java -io 读取文件操作

    主要分为字节读取和字符读取,字节读取可以一个一个读取和字节数组读取,字符读取同样之,字符读取适合文本读取,字节读取皆可以 这里直接上代码,读取文件的9个小demo package com.io; im ...

  9. java实现读取文件大全

    1.按字节读取文件内容 2.按字符读取文件内容 3.按行读取文件内容 4.随机读取文件内容 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件 ...

随机推荐

  1. boostrap 模态框

    <div class="modal fade" id="myModal" tabindex="-1" role="dialo ...

  2. PHP中 magic&lowbar;quotes&lowbar;gpc 和 magic&lowbar;quotes&lowbar;runtime 区别及其反斜线转义问题

    php中关于反斜线转义: php中数据的魔法引用函数 magic_quotes_gpc  或 magic_quotes_runtime     设置为on时,当数据遇到 单引号' 和 双引号&quot ...

  3. JDBC加载过程

    jdbc载入的过程如图所看到的. 桥接模式请參照:设计模式:桥接模式 blog目的:与图说话 版权声明:本文博客原创文章,博客,未经同意,不得转载.

  4. node-xlsx

    1.安装 必要组件 npm install node-xlsx -S /*Babel默认只转换新的JavaScript句法(syntax),而不转换新的API,比如Iterator.Generator ...

  5. Python&lowbar;NAT

    sockMiddle_server.py import sys import socket import threading #回复消息,原样返回 def replyMessage(conn): wh ...

  6. &lbrack;开发技巧&rsqb;&&num;183&semi;Numpy中对axis的理解与应用

    [开发技巧]·Numpy中对axis的理解与应用 1.问题描述 在使用Numpy时我们经常要对Array进行操作,如果需要针对Array的某一个纬度进行操作时,就会用到axis参数. 一般的教程都是针 ...

  7. 7&period;11 cookie 失效后 ,重新登陆 页面 可能跳出 框架 ,只剩主题 部分 ,

    判断地址 不在  框架里  (项目  地址栏一般 都是 首页地址 ) function url(){ var page=getpage(); if(window==top&&(page ...

  8. log4j2配置文件

    项目里面经常用到日志,Java开发一般用log4j.slf4j这些框架,看着配置文件有点懵.这几天看公司代码的时候,也有用到log4j,感觉要复杂一点.在本地打log,也有打到hive里面存的.看了一 ...

  9. Java:Maven依赖包下载

    Maven依赖的包可以到Maven的中心仓库 http://search.maven.org/#browse 进行查找下载 例如需要MyBatis的依赖包,搜索mybatis,然后选择正确的路径,复制 ...

  10. HH去散步(bzoj 1875)

    Description HH有个一成不变的习惯,喜欢饭后百步走.所谓百步走,就是散步,就是在一定的时间 内,走过一定的距离. 但是同时HH又是个喜欢变化的人,所以他不会立刻沿着刚刚走来的路走回. 又因 ...