java中多种方式读文件
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java中多种方式读文件
一、多种方式读文件内容。
1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容
*/
impo rt ja va.io.Buff eredR eader;
im portjava.io.Fi le;
impor t jav a.io.FileI nputS tream;
im portjava.io.Fi leRea der;
impo rt ja va.io.IOEx cepti on;
impor t jav a.io.Input Strea m;
i mport java.io.I nputS tream Reade r;
i mport java.io.R andom Acces sFile;
im portjava.io.Re ader;
pub lic c lassReadF romFi le {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
* @par am fi leNam e 文件的名
*/
pub lic s tatic void read FileB yByte s(Str ing f ileNa me){
File file = ne w Fil e(fil eName);
I nputS tream in = null;
tr y {
Syste m.out.prin tln("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = ne w Fil eInpu tStre am(fi le);
inttempb yte;
whil e((te mpbyt e=in.read()) != -1){
Sys tem.o ut.wr ite(t empby te);
}
i n.clo se();
} c atch(IOEx cepti on e) {
e.prin tStac kTrac e();
retu rn;
}
tr y {
Syste m.out.prin tln("以字节为单位读取文件内容,一次读多个字节:");
//一次读多个字节
byt e[] t empby tes = newbyte[100];
int byte read= 0;
in = newFileI nputS tream(file Name);
Re adFro mFile.show Avail ableB ytes(in);
//读入多个字节到字节数组中,byte read为一次读入的字节数
while ((by terea d = i n.rea d(tem pbyte s)) != -1){
Sy stem.out.w rite(tempb ytes, 0, b ytere ad);
}
} catc h (Ex cepti on e1) {
e1.pr intSt ackTr ace();
}final ly {
if (in != null){
t ry {
in.c lose();
} catc h (IO Excep tione1) {
}
}
}
}
/**
*以字符为单位读取文件,常用于读文本,数字等类型的文件
* @par am fi leNam e 文件名
*/
publ ic st aticvoidreadF ileBy Chars(Stri ng fi leNam e){
Filefile= new File(file Name);
Re aderreade r = n ull;
try{
Sy stem.out.p rintl n("以字符为单位读取文件内容,一次读一个字节:"); // 一次读一个字符
read er =new I nputS tream Reade r(new File Input Strea m(fil e));
inttempc har;
whil e ((t empch ar =reade r.rea d())!= -1){
//对于wi ndows下,rn这两个字符在一起时,表示一个换行。
//但如果这两个字符分开显示时,会换两次行。
//因此,屏蔽掉r,或者屏蔽n。
否则,将会多出很多空行。
if(((ch ar)te mpcha r) != 'r'){
Sy stem.out.p rint((char)temp char);
}
}
r eader.clos e();
} ca tch (Excep tione) {
e.pr intSt ackTr ace();
}
try{
Sy stem.out.p rintl n("以字符为单位读取文件内容,一次读多个字节:"); //一次读多个字符
char[] tem pchar s = n ew ch ar[30];
i nt ch arrea d = 0;
re ader= new Inpu tStre amRea der(n ew Fi leInp utStr eam(f ileNa me));
//读入多个字符到字符数组中,cha rread为一次读取字符数
while ((ch arrea d = r eader.read(temp chars))!=-1){
//同样屏蔽掉r不显示
if ((ch arrea d ==tempc hars.lengt h)&&(tempc hars[tempc hars.lengt h-1]!= 'r')){Syst em.ou t.pri nt(te mpcha rs);
}els e{
f or (i nt i=0; i<charr ead;i++){
if(tempc hars[i] == 'r'){
co ntinu e;
}else{
Sys tem.o ut.pr int(t empch ars[i]);
}
}
}
}
} c atch(Exce ption e1){
e1.prin tStac kTrac e();
}fin ally{
if (rea der != nul l){
try {
rea der.c lose();
} catc h (IO Excep tione1) {
}
}
}
}
/**
*以行为单位读取文件,常用于读面向行的格式化文件
* @p aramfileN ame 文件名
*/
pu blicstati c voi d rea dFile ByLin es(St ringfileN ame){
Fil e fil e = n ew Fi le(fi leNam e);
Buffe redRe aderreade r = n ull;
try{
Sy stem.out.p rintl n("以行为单位读取文件内容,一次读一整行:");
rea der = newBuffe redRe ader(new F ileRe ader(file));
S tring temp Strin g = n ull;
intline= 1;
//一次读入一行,直到读入n ull为文件结束
while ((te mpStr ing = read er.re adLin e())!= nu ll){
//显示行号
S ystem.out.print ln("l ine " + li ne +": "+ tem pStri ng);
line++;
}
re ader.close();
} cat ch (I OExce ption e) {
e.p rintS tackT race();
if(read er != null){
t ry {
read er.cl ose();
}catch (IOE xcept ion e1) {
}
}
}
}
/**
*随机读取文件内容
* @pa ram f ileNa me 文件名
*/
pub lic s tatic void read FileB yRand omAcc ess(S tring file Name){
Ra ndomA ccess Filerando mFile = nu ll;
try {
Sys tem.o ut.pr intln("随机读取一段文件内容:");
//打开一个随机访问文件流,按只读方式
rando mFile = ne w Ran domAc cessF ile(f ileNa me, "r");
// 文件长度,字节数
l ong f ileLe ngth= ran domFi le.le ngth();
// 读文件的起始位置
int begi nInde x = (fileL ength > 4) ? 4: 0;
//将读文件的开始位置移到b eginI ndex位置。
r andom File.seek(begin Index);
b yte[] byte s = n ew by te[10];
i nt by terea d = 0;
//一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
//将一次读取的字节数赋给byte read
whil e ((b ytere ad =rando mFile.read(byte s)) != -1){
Sy stem.out.w rite(bytes, 0,byter ead);
}
} cat ch (I OExce ption e){
e.pr intSt ackTr ace();
}final ly {
if (rando mFile != n ull){
try {
r andom File.close();
} cat ch (I OExce ption e1){
}
}
}
}
/**
* 显示输入流中还剩的字节数
*/
pr ivate stat ic vo id sh owAva ilabl eByte s(Inp utStr eam i n){
try {
Sys tem.o ut.pr intln("当前字节输入流中的字节数为:" +in.av ailab le());
}catch (IOE xcept ion e) {
e.pri ntSta ckTra ce();
}
}
pu blicstati c voi d mai n(Str ing[] args) {
Strin g fil eName = "C:/tem p/new Temp.txt";
Rea dFrom File.readF ileBy Bytes(file Name);
Re adFro mFile.read FileB yChar s(fil eName);
R eadFr omFil e.rea dFile ByLin es(fi leNam e);
ReadF romFi le.re adFil eByRa ndomA ccess(file Name);
}
}
二、将内容追加到文件尾部
im portjava.io.Fi leWri ter;
impo rt ja va.io.IOEx cepti on;
impor t jav a.io.Rando mAcce ssFil e;
/**
*将内容追加到文件尾部
*/
pub lic c lassAppen dToFi le {
/**
* A方法追加文件:使用Ra ndomA ccess File
* @p aramfileN ame 文件名
* @par am co ntent追加的内容
*/
pub lic s tatic void appe ndMet hodA(Strin g fil eName,
St ringconte nt){
try{
//打开一个随机访问文件流,按读写方式
Rando mAcce ssFil e ran domFi le =new R andom Acces sFile(file Name, "rw"); // 文件长度,字节数
lon g fil eLeng th =rando mFile.leng th();
//将写文件指针移到文件尾。
ra ndomF ile.s eek(f ileLe ngth);
ra ndomF ile.w riteB ytes(conte nt);
rand omFil e.clo se();
} c atch(IOEx cepti on e){
e.print Stack Trace();
}
}
/**
* B方法追加文件:使用Fi leWri ter
* @pa ram f ileNa me
* @par am co ntent
*/
publ ic st aticvoidappen dMeth odB(S tring file Name, Stri ng co ntent){
t ry {
//打开一个写文件器,构造函数中的第二个参数tr ue表示以追加形式写文件F ileWr iterwrite r = n ew Fi leWri ter(f ileNa me, t rue);
wri ter.w rite(conte nt);
writ er.cl ose();
}catch (IOE xcept ion e) {
e.pri ntSta ckTra ce();
}
}
pu blicstati c voi d mai n(Str ing[] args) {
Strin g fil eName = "C:/tem p/new Temp.txt";
Str ing c onten t = "new a ppend!";
//按方法A追加文件
App endTo File.appen dMeth odA(f ileNa me, c onten t);
Appen dToFi le.ap pendM ethod A(fil eName, "ap pendend.n");
//显示文件内容
Read FromF ile.r eadFi leByL ines(fileN ame);
//按方法B追加文件
A ppend ToFil e.app endMe thodB(file Name, cont ent);
App endTo File.appen dMeth odB(f ileNa me, "appen d end. n");
//显示文件内容
Re adFro mFile.read FileB yLine s(fil eName);
}
}
。