java文件读写程序员代码_java读取文件的基本操作

import java.io.FileInputStream;

/**

* 使用FileInputStream读取文件

*/

public class FileRead {

/**

* @param args

*/

public static void main(String[] args) {

// 读取文件操作

// 1.通过 fis.read()方法读取,一个字节一个字节读取,对数据进行循环遍历

// ReadFileToint();

// 2.通过fis.read(data,0,length)方法读取。把数据一次全部读到data字节数组里面

ReadFile();

}

public static void ReadFileToint() {

// 声明流对象

FileInputStream fis = null;

try {

// 创建流对象

fis = new FileInputStream("d:\\test\\a.txt");

// 读取数据,并将读取到的数据存储到数组中

byte[] data = new byte[1024]; // 数据存储的数组

int i = 0; // 当前下标

// 读取流中的第一个字节数据

int n = fis.read();

// 依次读取后续的数据

while (n != -1) { // 未到达流的末尾

// 将有效数据存储到数组中

data[i] = (byte) n;

// 下标增加

i++;

// 读取下一个字节的数据

n = fis.read();

}

// 解析数据

String s = new String(data, 0, i);

// 输出字符串

System.out.println(s);

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

// 关闭流,释放资源

fis.close();

} catch (Exception e) {

}

}

}

public static void ReadFile() {

// 声明流对象

FileInputStream fis = null;

try {

// 创建流对象

fis = new FileInputStream("d:\\test\\a.txt");

// 读取数据,并将读取到的数据存储到数组中

byte[] data = new byte[1024]; // 数据存储的数组

int i = fis.read(data);

// 解析数据

String s = new String(data, 0, i);

String[] ssStrings = s.split("\r\n");

for (String b : ssStrings) {

System.out.println(b.replace('|', ' '));

}

// 输出字符串

System.out.println(s);

/*

* 其实懂正则表达式的应该已经发现了,是的,“.”是正则表达式的元字符,匹配除换行符以外的任意字符,所以replaceAll、

* replaceFirst才出现了这样的结果。

*

* 而replace没有用到正则表达式,但会把所有“.”替换掉,很多人可能会误解replace是替换单个,而replaceAll是替换全部

* ,其实这是错的(我以前也是这么想的- -)。replace只是没有用到正则表达式,但会替换所有匹配的字符串。

* 到这里一些不懂正则表达式的小伙伴可能就要喊坑爹了

* ,“那我不想用正则表达式去替换第一个字符串肿么办?”其实也很简单,只要将元字符串转义就行了

* 。s.replaceFirst("\\.", "#")

*/

/*

* 这里给个会被正则表达式识别的字符列表: .匹配除换行符以外的任意字符 ^匹配字符串的开始 $匹配字符串的结束* 重复零次或更多次

* +重复一次或更多次 ?重复零次或一次

*/

String ss = "my.test.txt";

String[] myStrings = ss.split("\\.", 2);

for (String b : myStrings) {

System.out.println(b);

}

System.out.println(ss.replace(".", "#"));

System.out.println(ss.replaceAll(".", "#"));

System.out.println(ss.replaceFirst(".", "#"));

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

// 关闭流,释放资源

fis.close();

} catch (Exception e) {

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值