java文件流操作

java中多种方式读文件 
一、多种方式读文件内容。 
1
、按字节读取文件内容  InputStream 读取的是字节 
2
、按字符读取文件内容  InputStreamReader 读取的是字符 
3
、按行读取文件内容    BufferredReader 可以读取行 
4
、随机读取文件内容 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.RandomAccessFile; 
import java.io.Reader; 
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下,rn这两个字符在一起时,表示一个换行。 
//
但如果这两个字符分开显示时,会换两次行。 
//
因此,屏蔽掉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(); 



public static void main(String[] args) { 
String fileName = "C:/temp/newTemp.txt"; 
ReadFromFile.readFileByBytes(fileName); 
ReadFromFile.readFileByChars(fileName); 
ReadFromFile.readFileByLines(fileName); 
ReadFromFile.readFileByRandomAccess(fileName); 



二、将内容追加到文件尾部 

import java.io.FileWriter; 
import java.io.IOException; 
import java.io.RandomAccessFile; 

/** 
*
将内容追加到文件尾部 
*/ 
public class AppendToFile { 

/** 
* A
方法追加文件:使用RandomAccessFile 
* @param fileName
文件名 
* @param content
追加的内容 
*/ 
public static void appendMethodA(String fileName, 

String content){ 
try { 
//
打开一个随机访问文件流,按读写方式 
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); 
//
文件长度,字节数 
long fileLength = randomFile.length(); 
//
将写文件指针移到文件尾。 
randomFile.seek(fileLength); 
randomFile.writeBytes(content); 
randomFile.close(); 
} catch (IOException e){ 
e.printStackTrace(); 


/** 
* B
方法追加文件:使用FileWriter 
* @param fileName 
* @param content 
*/ 
public static void appendMethodB(String fileName, String content){ 
try { 
//
打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 
FileWriter writer = new FileWriter(fileName, true); 
writer.write(content); 
writer.close(); 
} catch (IOException e) { 
e.printStackTrace(); 



public static void main(String[] args) { 
String fileName = "C:/temp/newTemp.txt"; 
String content = "new append!"; 
//
按方法A追加文件 
AppendToFile.appendMethodA(fileName, content); 
AppendToFile.appendMethodA(fileName, "append end. n"); 
//
显示文件内容 
ReadFromFile.readFileByLines(fileName); 
//
按方法B追加文件 
AppendToFile.appendMethodB(fileName, content); 
AppendToFile.appendMethodB(fileName, "append end. n"); 
//
显示文件内容 
ReadFromFile.readFileByLines(fileName); 

 

JAVA里常用的对文件流的读与写

用读配置文件来举例:

FileReader fread;
BufferedReader buff;
String Line;

String[] Get=new String[200];

fread=new FileReader("配置文件名");
buff=new BufferedReader(fread);

Line=buff.readLine();//从文件读取一行字符串
Get =Line.split(",");

……

buff.close();
fread.close();

用写日志文件的一个类来举例:

import java.io.*;
import java.util.Calendar;

public class CDbLog
{
 
 private String LOGPATH=null;
 private String LOGFILE=null;
 
 
 public int outlog(String outmsg){
  try{
   LOGPATH="./log/";
   LOGFILE="DbExpLog";
   String filearr[]=null;
   long  modtime = 300000000000000L;
   
   File pathobj = new File(LOGPATH); //
日志路径对象
   pathobj.mkdirs();     
   
   filearr = pathobj.list();   //列出路径下所有日志文件
   
   if(filearr != null){
    System.out.println("*****   The Log_file number:"+filearr.length+" , The Log_file name:"+LOGFILE+getD()+".log"+"  *****");
    int j =-1;
    if(filearr.length >= 30){  //如果日志文件的个数达到30个,就将最早的那个文件删除
     for(int i=0;i<30;i++){
      File delfiles = new File(LOGPATH,filearr[i]);
      if(delfiles.lastModified()<modtime){
       modtime = delfiles.lastModified();
       j = i;
      }
     }
     File delfile = new File(LOGPATH,filearr[j]);
     delfile.delete();
    }
   }
   
   LOGFILE = LOGFILE+getD()+".log";

   File fileobj = new File(LOGPATH+LOGFILE);
      
   fileobj.createNewFile();
   FileWriter fwrite;
   BufferedWriter buff;
   
   fwrite=new FileWriter(LOGPATH+LOGFILE,true);//
追加写的方式
   buff=new BufferedWriter(fwrite);
   buff.write(getT());
   buff.write(outmsg);
   buff.close();
   fwrite.close();
  }catch(Exception e){
   System.out.println(e);
   return -1;
  }
  return 0;
 }//END outlog()


 private  String getT()
 {
  int y,m,d,h,mi,s;
  String strTime="";
  Calendar cal=Calendar.getInstance();
  y=cal.get(Calendar.YEAR);
  m=cal.get(Calendar.MONTH)+1;
  d=cal.get(Calendar.DATE);
  h=cal.get(Calendar.HOUR_OF_DAY);
  mi=cal.get(Calendar.MINUTE);
  s=cal.get(Calendar.SECOND);
  strTime="time:"+y+"-"+m+"-"+d+"  "+h+":"+mi+":"+s;
  strTime="\r\n----------------"+strTime+"---------------------\r\n";
  return strTime;
 }//END getT()
 private  String getD()
 {
  int y,m,d;//h,mi,s;
  String strDate="";
  Calendar cal=Calendar.getInstance();
  y=cal.get(Calendar.YEAR);
  m=cal.get(Calendar.MONTH)+1;
  d=cal.get(Calendar.DATE);
  //h=cal.get(Calendar.HOUR_OF_DAY);
  //mi=cal.get(Calendar.MINUTE);
  //s=cal.get(Calendar.SECOND);
  strDate=y+"-"+m+"-"+d;
  
  return strDate;
 }//end getD()
}//end class

1)      输入输出流(程序从某个地方数据,程序将数据保存到某个地方)

输入流是将数据从数据源传送到程序,输出流是将数据从程序送到期望的地方。(什么是数据源是关键,不要混淆输入和输出)

字节:InputStreamOutputStream

双字节:ReaderWriter

ReaderWriter用于读取双字节的Unicode的字符,读取中文时不会出现乱码

类的层次,继承关系,这里主要介绍文件的读写,即子类FileInputStream等。

2)      标准输入输出流

System.in  接受用户在标准io设备上的输入,一般是键盘。

System.out

System.err

3)      流的常用方法

以上四个流的常用方法。

读取文件的操作:

数据源是文件,程序从文件里要数据,应该用输入流。

InputStream使用在二进制文件上,比如应用程序,图片,媒体文件等,Reader用在文本文件,比如log文件,txt文件等。

InputStream的子类FileInputStream的构造方法

构造方法摘要

FileInputStream(File file)
          
通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。

FileInputStream(FileDescriptor fdObj)
          
通过使用文件描述符 fdObj 创建一个 FileInputStream,该文件描述符表示到文件系统中某个实际文件的现有连接。

FileInputStream(String name)
          
通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。

Reader子类InputStreamReader的构造方法

构造方法摘要

InputStreamReader(InputStream in)
          
创建一个使用默认字符集的 InputStreamReader

InputStreamReader(InputStream in, Charset cs)
          
创建使用给定字符集的 InputStreamReader

InputStreamReader(InputStream in, CharsetDecoder dec)
          
创建使用给定字符集解码器的 InputStreamReader

InputStreamReader(InputStream in, String charsetName)
          
创建使用指定字符集的 InputStreamReader

二者使用上的差异(inputstream读取unicode中文文件会产生乱码,见代码文件,略)

将内容保存到文件的操作

OutputStreamWriter类。

ReadFile.java

package FileOperation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

//比较InputStreamReadertxt文件,据说InputStream会产生乱码,但兵马俑。不知道为什么
public class ReadFile {


public static void main(String[] args) throws IOException {

if(args == null || args.length < 1)
{
System.out.println("
缺少参数字符串给出要读取的文件的位置");
}

//传入一个参数指定文件位置
File file = new File(args[0]);

//调用readFileUsingInputStream(file)方法读取件
System.out.println("使用 InputStream 读取文件 " + file.getAbsolutePath() +
",
内容为: ");
System.out.println(readFileUsingInputStream(file));


//调用readFileUsingReader(file)读文件
System.out.println("使用 Reader 读取文件 " + file.getAbsolutePath() +
",
内容为: ");
System.out.println(readFileUsingReader(file));

}



/*InputStream流读文件,注意这里抛出了异常,可能出现在ins.close();当你在方法内部
* 写到某个语句可能产生异常的时候,会有提示你在方法头声明异常,我们也可以看到throws
* 的异常也并不一定要急着去处理,在main方法里调用此方法时再次把异常往上抛,并没有去处理*/
public static String readFileUsingInputStream(File file) throws IOException
{
InputStream ins =
null;
StringBuffer buffer =
new StringBuffer();//用一个buffer保存读取的数据

try{
ins =
new FileInputStream(file);//FileInputStream的构造方法,指定某个文件

byte[] tmp = new byte[10];

int length = 0;

//int read(byte[] a)方法,从输入流读取数据,并存储于缓冲区a内,返回值为读取字节数
//流读取最后完好的保存了换行 空格
while((length = ins.read(tmp)) != -1)//每次读10字节
{
buffer.append(
new String(tmp,0,length));
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(ins != null)
{
ins.close();
}
}


return buffer.toString();
}


//同上
public static String readFileUsingReader(File file) throws IOException
{
Reader reader =
null;

StringBuffer buffer =
new StringBuffer();

try{
reader =
new InputStreamReader(new FileInputStream(file));

char[] tmp = new char[10];//字符流,注意跟上面的缓冲区的区别

int length = 0;

while((length = reader.read(tmp)) != -1)
{
buffer.append(
new String(tmp,0,length));
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(reader != null)
{
reader.close();
}
}


return buffer.toString();
}

}

使用 InputStream 读取文件  D:\filetest.txt, 内容为:
标题:静夜思

作者:李白

床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。


使用 Reader 读取文件  D:\filetest.txt, 内容为:
标题:静夜思

作者:李白

床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
 

WriteFile

package FileOperation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

public class WriteFile {


public static void writeFileUsingOutputStream(File file,String content) throws Throwable
{

if(file.createNewFile())
System.out.println("
已建立新文件 " + file.getAbsolutePath());

OutputStream ous =
null;

try{
ous =
new FileOutputStream(file);
ous.write(content.getBytes());
ous.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(ous != null)
ous.close();
}
System.out.println("
已写入文件 " + file.getAbsolutePath());
}



public static void writeFileUsingWriter(File file,String content) throws IOException
{

if(file.createNewFile())
System.out.println("
已建立新文件 " + file.getAbsolutePath());

Writer writer =
null;

try{
//注意writer的生成,由中间过程FileOutputStream转化了一次
writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write(content);
writer.flush();
//强制将缓存里的数据输出
}catch(Exception e){
e.printStackTrace();
}
finally{
if(writer != null)
writer.close();
}
System.out.println("
已写入文件 " + file.getAbsolutePath());
}



public static void main(String[] args) throws Throwable {

System.out.println("
请输入文件内容,#符号结束输入:");

//注意writerreader对象都要通过另一个流生成
Reader reader = new InputStreamReader(System.in);//注意标准输入的用法

StringBuffer buffer = new StringBuffer();
char ch;
//输入内容都放入buffer
while((ch = (char) reader.read()) != '#')
buffer.append(ch);


//分别用两种方法来保存内容
writeFileUsingOutputStream(new File("C:\\output_stream.txt"), buffer.toString());
writeFileUsingWriter(
new File("C:\\ouput_writer.txt"),buffer.toString());
}

}

请输入文件内容,#符号结束输入:
标题:茕茕白兔
选自:诗经

茕茕白兔,
东奔西顾。
衣不如新,
人不如故。
#
已建立新文件  C:\output_stream.txt
已写入文件  C:\output_stream.txt
已建立新文件  C:\ouput_writer.txt
已写入文件  C:\ouput_writer.txt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫一样的女子245

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值