读取文件之<绝对路径>与<相对路径>
前言:字符流、字节流读取文件,下面的代码是在网上找到的一个各种文件读取方式,还算比较详细,分享给大家。
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开发中相对路径却拿不到对应的文件。
读取文件之<绝对路径>与<相对路径>的更多相关文章
- 读取文件不是真实的具体路径 setZh.ini
读取 c:\windows\Syswow64\XX\XX.ini 时内容不正确. 发现真实文件为: C:\Users\用户名\AppData\Local\VirtualStore\Windows\Sy ...
- JavaWeb中读取文件资源的路径问题
在做javaweb开发的时候,我们可能会需要从本地硬盘上读取某一个文件资源,或者修改某一个文件,这个时候就需要先找到这个文件,然后用FileInputStrem等文件字节.字符流来将这个文件读取到内存 ...
- Java获取路径方法&相对路径读取xml文件方法
(1).request.getRealPath("/");//不推荐使用获取工程的根路径 (2).request.getRealPath(request.getRequestURI ...
- java 使用相对路径读取文件
java 使用相对路径读取文件 1.java project环境,使用java.io用相对路径读取文件的例子: *目录结构: DecisionTree |___src ...
- (转)C#读取文件路径
//获取包含清单的已加载文件的路径或 UNC 位置. public static string sApplicationPath = Assembly.GetExecutingAssembly ( ) ...
- java 读取文件的路径
1. 通用定位到用户目录下: String userDir = System.getProperty("user.dir"); 2. web项目定位到WEB-INF/class ...
- python中读取文件数据时要注意文件路径
我们在用python进行数据处理时往往需要将文件中的数据取出来做一些处理,这时我们应该注意数据文件的路径.文件路径不对,回报如下错误: FileNotFoundError: File b'..Adve ...
- Java递归读取文件路径下所有文件名称并保存为Txt文档
本文用递归的方法实现读取一个路径下面的所有文件并将文件名称保存到Txt文件中,亲测可用. 递归读取文件路径下的所有文件: /** * 递归读取文件路径下的所有文件 * * @param path * ...
- Java FileReader使用相对路径读取文件
Java FileReader使用相对路径读取文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 在进行编程时需要时常更换主机进行测试,如果使用绝对路径则需要经常更改,为此使用相对路径是一个 ...
- java中使用相对路径读取文件的写法总结 ,以及getResourceAsStream() (转)
https://blog.csdn.net/my__sun_/article/details/74450241 读取文件的写法,相对路径 在当前的目录结构中读取test.txt的有四种写法 简单粗暴的 ...
随机推荐
- 【云计算】mesos+marathon 服务发现、负载均衡、监控告警方案
Mesos-dns 和 Marathon-lb 是mesosphere 官网提供的两种服务发现和负载均衡工具.官方的文档主要针对DCOS,针对其它系统的相关中文文档不多,下面是我在Centos7上的安 ...
- Kubernetes用户指南(三)--在生产环境中使用Pod来工作、管理部署
一.在生产环境中使用Pod来工作 本节将介绍一些在生产环境中运行应用非常有用的功能. 1.持久化存储 容器的文件系统只有当容器正常运行时有效,一旦容器奔溃或者重启,所有对文件系统的修改将会丢失,从一个 ...
- Tempter of the Bone——DFS(王道)
Problem Description The doggie found a bone in an ancient maze, which fascinated him a lot. However, ...
- EffectiveJava(24)使用@SuppressWarnings("unchecked")消除非受检警告
-..使用泛型编程时,会遇到许多编译器警告,如:非受检强制转化警告,非受检方法调用警告,非受检普通数组创建警告,费受精转换警告.这次的内容就是遇到这些警告的时候你该怎么办. PS:非受检警告就是代码上 ...
- Rails生成随机字符串及加解密
1.生成安全的base64字符串 key = SecureRandom.urlsafe_base64
- sql中limit和汇总函数的集合使用
limit和求和一起 select SUM(A.high) from (select * from minute1_K order by DateTime desc limit 10) A limit ...
- 《Java程序猿面试笔试宝典》之Statickeyword有哪些作用
statickeyword主要有两种作用:第一,仅仅想为某特定数据类型或对象分配单一的存储空间,而与创建对象的个数无关.第二,希望某个方法或属性与类而不是对象关联在一起,也就是说,在不创建对象的情况下 ...
- HDU 4632 Palindrome subsequence(区间dp)
Palindrome subsequence Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65535 K (Java/ ...
- The user specified as a definer ('root'@'%') does not exist
通常是因为root用户对全局host无訪问权限.因此仅仅要给root用户加入一个訪问权限就可以. 解决的方法: 登陆mysql .运行 mysql -u root -pPasswd mysql ...
- lucene: nDocs must be > 0查询异常解决
nDocs must be > 0 // 函数search(query,filter,n),其中query是查询条件,filter是过滤器,n查询数量,异常消息意思就是n参数的值必须大于 ...