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

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. Vue组件基础知识总结

    组件系统是Vue.js其中一个重要的概念,它提供了一种抽象,让我们可以使用独立可复用的小组件来构建大型应用,任意类型的应用界面都可以抽象为一个组件树. 那么什么是组件呢?组件可以扩展HTML元素,封装 ...

  2. mac 777权限设置

    1. cd 你的文件夹路径的上一级目录. 2. sudo chmod -R 777 你的文件夹名. 3. 输入密码. 4.成功

  3. Android之——获取手机安装的应用程序

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47114331 前几篇有关Android的博文中.向大家介绍了几个项目中经常使用的有 ...

  4. 倍福TwinCAT(贝福Beckhoff)常见问题(FAQ)-如何设置PLC的扫描周期,运行周期

    双击PlcTask,然后再Cycle ticks中可以修改PLC的扫描周期,例如修改为2ms   为了验证是否真的是2ms,可以在程序中跟计数器绑定使用,PLC2ms扫描一次,计数器也是每个周期增加0 ...

  5. Vue 组件开发demo

    1.代码地址 github:https://github.com/MengFangui/VueComponentDemo- 2.关键代码 (1)main.js //引入vue import Vue f ...

  6. Visual studio C++ MFC之点击按钮(菜单栏)生成新窗口

    背景 当前做的APP有菜单栏,菜单栏有一项需要对下位机相关参数进行设置,则必须弹出一个窗口来实现设置操作.本篇即对点击菜单栏生成新的窗口,在新的窗口内完成相应计划后结束新窗口并返回原窗口的方法进行简述 ...

  7. C#运用反射调用其他程序集中的代码

    加载程序集 AssMedicalAdvice = Assembly.LoadFrom(Path.Combine(Environment.CurrentDirectory, "Inscript ...

  8. js基础 js自执行函数、调用递归函数、圆括号运算符、函数声明的提升 js 布尔值 ASP.NET MVC中设置跨域

    js基础 目录 javascript基础 ESMAScript数据类型 DOM JS常用方法 回到顶部 javascript基础 常说的js包括三个部分:dom(文档document).bom(浏览器 ...

  9. eclipse日志

    注意包别引入错: import org.slf4j.Logger; import org.slf4j.LoggerFactory; private static final Logger log = ...

  10. linux 实时显示文件的内容

    1. watch -n 1 aa.txt  #每个1秒显示aa.txt的内容 2. tail -f ***.log Linux shell中有一个tail命令,常用来显示一个文件的最后n行文档内容 但 ...