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

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. linux下javadoc生成文件出现中文乱码

    javadoc命令的正确使用姿势 javadoc -d apidoc -windowtitle Testing -doctitle 'The API of javadoc' -header 'My c ...

  2. mybatis 一对多

    person package com.kerwin.mybatis.pojo; import java.util.List; public class Person { private int id; ...

  3. Spring Ajax一个简单样例

    配置不说了.要在前面helloworld的样例基础上弄. 相同在hello下新建ajax.jsp <%@ page language="java" contentType=& ...

  4. Unity多媒体展示项目经验分享-ImageEffect+动态绑定

    Unity多媒体展示项目经验分享-ImageEffect+动态绑定+网络通信 <ignore_js_op> “海尔科技展墙”是去年年初我们为上海家电博览会制作的一个多媒体展项,有限的工期以 ...

  5. 网络编程——The C10K Problem(C10K = connection 10 kilo 问题)。k 表示 kilo,即 1000

    The C10K problem翻译 (C10K = connection 10 kilo 问题).k 表示 kilo,即 1000 比如:kilometer(千米), kilogram(千克). 如 ...

  6. Velocity中文乱码问题解决方法

    http://yonge812.iteye.com/blog/1010290 Velocity中文乱码问题需要注意一下几点: 1.eclipse默认编码方式 2.页面的编码方式 3.volocity模 ...

  7. 【MyBatis学习09】高级映射之一对多查询

    上一篇博文总结了一下一对一的映射,本文主要总结一下一对多的映射,从上一篇文章中的映射关系图中可知,订单项和订单明细是一对多的关系,所以本文主要来查询订单表,然后关联订单明细表,这样就有一对多的问题出来 ...

  8. linux 异步IO通信

    一. 回顾 做java开发的,一定对BIO,NIO,AIO通信很了解了,现在再在下面罗列一下: 同步阻塞IO(JAVA BIO):  同步并阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时 ...

  9. Note:pandas时间序列处理

    Note 1.Time Series #1 from datetime import datetime now=datetime.now() now.year now.month now.day #2 ...

  10. LeetCode 75 Sort Colors(颜色排序)

    翻译 给定一个包括红色.白色.蓝色这三个颜色对象的数组.对它们进行排序以使同样的颜色变成相邻的,其顺序是红色.白色.蓝色. 在这里,我们将使用数字0.1和2分别来代表红色.白色和蓝色. 原文 Give ...