前言:字符流、字节流读取文件,下面的代码是在网上找到的一个各种文件读取方式,还算比较详细,分享给大家。

public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
* @param fileName 文件的名
*/
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) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
* @param fileName 文件名
*/
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) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
* @param fileName 文件名
*/
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) {
}
}
}
}
/**
* 随机读取文件内容
* @param fileName 文件名
*/
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) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
* @param in
*/
private static void showAvailableBytes(InputStream in){
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
}

----绝对路径

*注意:相对路径的起始处无斜杆"/";

例如:filepath="resource/train.txt";
而不是filepath="/resource/train.txt"; //error!

在Web开发中尽量使用绝对路径,前一段路径无论是用的Windows或Linux开发,都可以利用 ServletActionContext.getServletContext().getRealPath(path);   来获取!

简单来说就是 路径的拼接 来组成要读取文件的绝对路径

----相对路径

使用java project环境,使用java.io用相对路径读取文件的例子:
 *目录结构:
  DecisionTree
            |___src
                 |___com.decisiontree.SamplesReader.java
            |___resource
                 |___train.txt,test.txt
 *SamplesReader.java:
  String filepath="resource/train.txt";//注意filepath的内容;
  File file=new File(filepath);
  ……

当然在Web开发中相对路径却拿不到对应的文件。

读取文件之<绝对路径>与<相对路径>的更多相关文章

  1. 读取文件不是真实的具体路径 setZh.ini

    读取 c:\windows\Syswow64\XX\XX.ini 时内容不正确. 发现真实文件为: C:\Users\用户名\AppData\Local\VirtualStore\Windows\Sy ...

  2. JavaWeb中读取文件资源的路径问题

    在做javaweb开发的时候,我们可能会需要从本地硬盘上读取某一个文件资源,或者修改某一个文件,这个时候就需要先找到这个文件,然后用FileInputStrem等文件字节.字符流来将这个文件读取到内存 ...

  3. Java获取路径方法&相对路径读取xml文件方法

    (1).request.getRealPath("/");//不推荐使用获取工程的根路径 (2).request.getRealPath(request.getRequestURI ...

  4. java 使用相对路径读取文件

    java 使用相对路径读取文件 1.java project环境,使用java.io用相对路径读取文件的例子: *目录结构:  DecisionTree            |___src      ...

  5. (转)C#读取文件路径

    //获取包含清单的已加载文件的路径或 UNC 位置. public static string sApplicationPath = Assembly.GetExecutingAssembly ( ) ...

  6. java 读取文件的路径

    1. 通用定位到用户目录下:   String userDir = System.getProperty("user.dir"); 2. web项目定位到WEB-INF/class ...

  7. python中读取文件数据时要注意文件路径

    我们在用python进行数据处理时往往需要将文件中的数据取出来做一些处理,这时我们应该注意数据文件的路径.文件路径不对,回报如下错误: FileNotFoundError: File b'..Adve ...

  8. Java递归读取文件路径下所有文件名称并保存为Txt文档

    本文用递归的方法实现读取一个路径下面的所有文件并将文件名称保存到Txt文件中,亲测可用. 递归读取文件路径下的所有文件: /** * 递归读取文件路径下的所有文件 * * @param path * ...

  9. Java FileReader使用相对路径读取文件

    Java FileReader使用相对路径读取文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 在进行编程时需要时常更换主机进行测试,如果使用绝对路径则需要经常更改,为此使用相对路径是一个 ...

  10. java中使用相对路径读取文件的写法总结 ,以及getResourceAsStream() (转)

    https://blog.csdn.net/my__sun_/article/details/74450241 读取文件的写法,相对路径 在当前的目录结构中读取test.txt的有四种写法 简单粗暴的 ...

随机推荐

  1. GLEW扩展库【转】

    http://blog.sina.com.cn/s/blog_4aff14d50100ydsy.html 一.关于GLEW扩展库: GLEW是一个跨平台的C++扩展库,基于OpenGL图形接口.使用O ...

  2. RequireJS全面讲解

    异步模块定义(AMD)  谈起RequireJS,你无法绕过提及JavaScript模块是什么,以及AMD是什么. JavaScript模块只是遵循SRP(Single Responsibility  ...

  3. Yii2系列教程六:集成编辑器

    上一篇文章我们实现了简单的用户权限管理,至于更先进的RBAC,我后面会单独出一篇文章来说说.在这一篇文章当中,我主要想写的是在Yii2中集成一个编辑器,因为在我们的实际开发当中,一个简单的textar ...

  4. vue总结介绍

    转自(https://zhuanlan.zhihu.com/p/23078117) 模板语法 Vue 提供了一堆数据绑定语法. {{ text }} 文本插值 <div v-html=" ...

  5. vue2自定义事件之$emit

    父组件: API上的解释不多: https://cn.vuejs.org/v2/api/#vm-emit vm.$emit( event, […args] ) 参数: {string} event [ ...

  6. Acer商祺x4610安装及使用

    一年前心血来潮买了部Acer商祺x4610,这两天把它装起来,记录下过程以备忘. 首先装操作系统,我装的是XP,这款电脑比较贴心的是开机时按住F12可以选择光盘还是硬盘启动,就不用到BIOS里面设置启 ...

  7. 64位系统注冊32位的directshow filter文件

    在SERVER2008上注冊自己写的directshow filter 的dll或者ax文件的时候总是提示 [Window Title] RegSvr32 [Content] 模块".\ba ...

  8. 【原】Ubuntu下使用teamviewer

    想尝试直接使用Xmanager打开Ubuntu桌面版,结果一直存在问题,迂回一下,尝试使用teamviewer解决,结果OK.办法如下: 在Ubuntu中,下载teamviewer,通过Windows ...

  9. php解耦的三种境界

    我们有三个类,Db,FileSystem,Session;实际业务需求要组合操作这三个类. 一.常规做法 class Db { public function read($id) { } } clas ...

  10. ural 1057 Amount of degrees 【数位dp】

    题意:求(x--y)区间转化为 c 进制 1 的个数为 k 的数的出现次数. 分析:发现其满足区间减法,所以能够求直接求0---x 的转化为 c 进制中 1 的个数为k的数的出现次数. 首先用一个数组 ...