多种方式读文件内容。

一、多种方式读文件内容。

1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容

001import java.io.BufferedReader;
002import java.io.File;
003import java.io.FileInputStream;
004import java.io.FileReader;
005import java.io.IOException;
006import java.io.InputStream;
007import java.io.InputStreamReader;
008import java.io.RandomAccessFile;
009import java.io.Reader;
010public class ReadFromFile {
011/**
012   * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
013   * @param fileName 文件的名
014   */
015public static void readFileByBytes(String fileName){
016   File file = new File(fileName);
017   InputStream in = null;
018   try {
019    System.out.println("以字节为单位读取文件内容,一次读一个字节:");
020    // 一次读一个字节
021    in = new FileInputStream(file);
022    int tempbyte;
023    while((tempbyte=in.read()) != -1){
024     System.out.write(tempbyte);
025    }
026    in.close();
027   } catch (IOException e) {
028    e.printStackTrace();
029    return;
030   }
031   try {
032    System.out.println("以字节为单位读取文件内容,一次读多个字节:");
033    //一次读多个字节
034    byte[] tempbytes = new byte[100];
035    int byteread = 0;
036    in = new FileInputStream(fileName);
037    ReadFromFile.showAvailableBytes(in);
038    //读入多个字节到字节数组中,byteread为一次读入的字节数
039    while ((byteread = in.read(tempbytes)) != -1){
040     System.out.write(tempbytes, 0, byteread);
041    }
042   } catch (Exception e1) {
043    e1.printStackTrace();
044   } finally {
045    if (in != null){
046     try {
047      in.close();
048     } catch (IOException e1) {
049     }
050    }
051   }
052}
053/**
054   * 以字符为单位读取文件,常用于读文本,数字等类型的文件
055   * @param fileName 文件名
056   */
057public static void readFileByChars(String fileName){
058   File file = new File(fileName);
059   Reader reader = null;
060   try {
061    System.out.println("以字符为单位读取文件内容,一次读一个字节:");
062    // 一次读一个字符
063    reader = new InputStreamReader(new FileInputStream(file));
064    int tempchar;
065    while ((tempchar = reader.read()) != -1){
066     //对于windows下,/r/n这两个字符在一起时,表示一个换行。
067     //但如果这两个字符分开显示时,会换两次行。
068     //因此,屏蔽掉/r,或者屏蔽/n。否则,将会多出很多空行。
069     if (((char)tempchar) != '/r'){
070      System.out.print((char)tempchar);
071     }
072    }
073    reader.close();
074   } catch (Exception e) {
075    e.printStackTrace();
076   }
077   try {
078    System.out.println("以字符为单位读取文件内容,一次读多个字节:");
079    //一次读多个字符
080    char[] tempchars = new char[30];
081    int charread = 0;
082    reader = new InputStreamReader(new FileInputStream(fileName));
083    //读入多个字符到字符数组中,charread为一次读取字符数
084    while ((charread = reader.read(tempchars))!=-1){
085     //同样屏蔽掉/r不显示
086     if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != '/r')){
087      System.out.print(tempchars);
088     }else{
089      for (int i=0; i<charread; i++){
090       if(tempchars[i] == '/r'){
091        continue;
092       }else{
093        System.out.print(tempchars[i]);
094       }
095      }
096     }
097    }
098  
099   } catch (Exception e1) {
100    e1.printStackTrace();
101   }finally {
102    if (reader != null){
103     try {
104      reader.close();
105     } catch (IOException e1) {
106     }
107    }
108   }
109}
110/**
111   * 以行为单位读取文件,常用于读面向行的格式化文件
112   * @param fileName 文件名
113   */
114public static void readFileByLines(String fileName){
115   File file = new File(fileName);
116   BufferedReader reader = null;
117   try {
118    System.out.println("以行为单位读取文件内容,一次读一整行:");
119    reader = new BufferedReader(new FileReader(file));
120    String tempString = null;
121    int line = 1;
122    //一次读入一行,直到读入null为文件结束
123    while ((tempString = reader.readLine()) != null){
124     //显示行号
125     System.out.println("line " + line + ": " + tempString);
126     line++;
127    }
128    reader.close();
129   } catch (IOException e) {
130    e.printStackTrace();
131   } finally {
132    if (reader != null){
133     try {
134      reader.close();
135     } catch (IOException e1) {
136     }
137    }
138   }
139}
140/**
141   * 随机读取文件内容
142   * @param fileName 文件名
143   */
144public static void readFileByRandomAccess(String fileName){
145   RandomAccessFile randomFile = null;
146   try {
147    System.out.println("随机读取一段文件内容:");
148    // 打开一个随机访问文件流,按只读方式
149    randomFile = new RandomAccessFile(fileName, "r");
150    // 文件长度,字节数
151    long fileLength = randomFile.length();
152    // 读文件的起始位置
153    int beginIndex = (fileLength > 4) ? 4 : 0;
154    //将读文件的开始位置移到beginIndex位置。
155    randomFile.seek(beginIndex);
156    byte[] bytes = new byte[10];
157    int byteread = 0;
158    //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
159    //将一次读取的字节数赋给byteread
160    while ((byteread = randomFile.read(bytes)) != -1){
161     System.out.write(bytes, 0, byteread);
162    }
163   } catch (IOException e){
164    e.printStackTrace();
165   } finally {
166    if (randomFile != null){
167     try {
168      randomFile.close();
169     } catch (IOException e1) {
170     }
171    }
172   }
173}
174/**
175   * 显示输入流中还剩的字节数
176   * @param in
177   */
178private static void showAvailableBytes(InputStream in){
179   try {
180    System.out.println("当前字节输入流中的字节数为:" + in.available());
181   } catch (IOException e) {
182    e.printStackTrace();
183   }
184}
185 
186public static void main(String[] args) {
187   String fileName = "C:/temp/newTemp.txt";
188   ReadFromFile.readFileByBytes(fileName);
189   ReadFromFile.readFileByChars(fileName);
190   ReadFromFile.readFileByLines(fileName);
191   ReadFromFile.readFileByRandomAccess(fileName);
192}
193}

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

001import java.io.FileWriter;
002import java.io.IOException;
003import java.io.RandomAccessFile;
004 
005/**
006* 将内容追加到文件尾部
007*/
008public class AppendToFile {
009 
010/**
011   * A方法追加文件:使用RandomAccessFile
012   * @param fileName 文件名
013   * @param content 追加的内容
014   */
015public static void appendMethodA(String fileName, String content){
016   try {
017    // 打开一个随机访问文件流,按读写方式
018    RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
019    // 文件长度,字节数
020    long fileLength = randomFile.length();
021    //将写文件指针移到文件尾。
022    randomFile.seek(fileLength);
023    randomFile.writeBytes(content);
024    randomFile.close();
025   } catch (IOException e){
026    e.printStackTrace();
027   }
028}
029/**
030   * B方法追加文件:使用FileWriter
031   * @param fileName
032   * @param content
033   */
034public static void appendMethodB(String fileName, String content){
035   try {
036    //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
037    FileWriter writer = new FileWriter(fileName, true);
038    writer.write(content);
039    writer.close();
040   } catch (IOException e) {
041    e.printStackTrace();
042   }
043}
044 
045public static void main(String[] args) {
046   String fileName = "C:/temp/newTemp.txt";
047   String content = "new append!";
048   //按方法A追加文件
049   AppendToFile.appendMethodA(fileName, content);
050   AppendToFile.appendMethodA(fileName, "append end. /n");
051   //显示文件内容
052   ReadFromFile.readFileByLines(fileName);
053   //按方法B追加文件
054   AppendToFile.appendMethodB(fileName, content);
055   AppendToFile.appendMethodB(fileName, "append end. /n");
056   //显示文件内容
057   ReadFromFile.readFileByLines(fileName);
058}
059}
060 
061三文件的各种操作类
062 
063import java.io.*;
064 
065/**
066* FileOperate.java
067* 文件的各种操作
068* @author 杨彩 http://blog.sina.com.cn/m/yangcai
069* 文件操作 1.0
070*/
071 
072public class FileOperate
073{
074 
075public FileOperate()
076{
077}
078/**
079* 新建目录
080*/
081public void newFolder(String folderPath)
082{
083try
084{
085String filePath = folderPath;
086filePath = filePath.toString();
087File myFilePath = new File(filePath);
088if(!myFilePath.exists())
089{
090myFilePath.mkdir();
091}
092System.out.println("新建目录操作 成功执行");
093}
094catch(Exception e)
095{
096System.out.println("新建目录操作出错");
097e.printStackTrace();
098}
099}
100/**
101* 新建文件
102*/
103public void newFile(String filePathAndName, String fileContent)
104{
105try
106{
107String filePath = filePathAndName;
108filePath = filePath.toString();
109File myFilePath = new File(filePath);
110if (!myFilePath.exists())
111{
112myFilePath.createNewFile();
113}
114FileWriter resultFile = new FileWriter(myFilePath);
115PrintWriter myFile = new PrintWriter(resultFile);
116String strContent = fileContent;
117myFile.println(strContent);
118resultFile.close();
119System.out.println("新建文件操作 成功执行");
120}
121catch (Exception e)
122{
123System.out.println("新建目录操作出错");
124e.printStackTrace();
125}
126}
127/**
128* 删除文件
129*/
130public void delFile(String filePathAndName)
131{
132try
133{
134String filePath = filePathAndName;
135filePath = filePath.toString();
136File myDelFile = new File(filePath);
137myDelFile.delete();
138System.out.println("删除文件操作 成功执行");
139}
140catch (Exception e)
141{
142System.out.println("删除文件操作出错");
143e.printStackTrace();
144}
145}
146/**
147* 删除文件夹
148*/
149public void delFolder(String folderPath)
150{
151try
152{
153delAllFile(folderPath); //删除完里面所有内容
154String filePath = folderPath;
155filePath = filePath.toString();
156File myFilePath = new File(filePath);
157if(myFilePath.delete()) { //删除空文件夹
158System.out.println("删除文件夹" + folderPath + "操作 成功执行");
159} else {
160System.out.println("删除文件夹" + folderPath + "操作 执行失败");
161}
162}
163catch (Exception e)
164{
165System.out.println("删除文件夹操作出错");
166e.printStackTrace();
167}
168}
169/**
170* 删除文件夹里面的所有文件
171* @param path String 文件夹路径 如 c:/fqf
172*/
173public void delAllFile(String path)
174{
175File file = new File(path);
176if(!file.exists())
177{
178return;
179}
180if(!file.isDirectory())
181{
182return;
183}
184String[] tempList = file.list();
185File temp = null;
186for (int i = 0; i < tempList.length; i++)
187{
188if(path.endsWith(File.separator))
189{
190temp = new File(path + tempList[i]);
191}
192else
193{
194temp = new File(path + File.separator + tempList[i]);
195}
196if (temp.isFile())
197{
198temp.delete();
199}
200if (temp.isDirectory())
201{
202//delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
203delFolder(path+ File.separatorChar + tempList[i]);//再删除空文件夹
204}
205}
206System.out.println("删除文件操作 成功执行");
207}
208/**
209* 复制单个文件
210* @param oldPath String 原文件路径 如:c:/fqf.txt
211* @param newPath String 复制后路径 如:f:/fqf.txt
212*/
213public void copyFile(String oldPath, String newPath)
214{
215try
216{
217int bytesum = 0;
218int byteread = 0;
219File oldfile = new File(oldPath);
220if (oldfile.exists())
221{
222//文件存在时
223InputStream inStream = new FileInputStream(oldPath); //读入原文件
224FileOutputStream fs = new FileOutputStream(newPath);
225byte[] buffer = new byte[1444];
226while ( (byteread = inStream.read(buffer)) != -1)
227{
228bytesum += byteread; //字节数 文件大小
229System.out.println(bytesum);
230fs.write(buffer, 0, byteread);
231}
232inStream.close();
233}
234System.out.println("删除文件夹操作 成功执行");
235}
236catch (Exception e)
237{
238System.out.println("复制单个文件操作出错");
239e.printStackTrace();
240}
241}
242/**
243* 复制整个文件夹内容
244* @param oldPath String 原文件路径 如:c:/fqf
245* @param newPath String 复制后路径 如:f:/fqf/ff
246*/
247public void copyFolder(String oldPath, String newPath)
248{
249try
250{
251(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
252File a=new File(oldPath);
253String[] file=a.list();
254File temp=null;
255for (int i = 0; i < file.length; i++)
256{
257if(oldPath.endsWith(File.separator))
258{
259temp=new File(oldPath+file[i]);
260}
261else
262{
263temp=new File(oldPath+File.separator+file[i]);
264}
265if(temp.isFile())
266{
267FileInputStream input = new FileInputStream(temp);
268FileOutputStream output = new FileOutputStream(newPath + "/" +
269(temp.getName()).toString());
270byte[] b = new byte[1024 * 5];
271int len;
272while ( (len = input.read(b)) != -1)
273{
274output.write(b, 0, len);
275}
276output.flush();
277output.close();
278input.close();
279}
280if(temp.isDirectory())
281{
282//如果是子文件夹
283copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
284}
285}
286System.out.println("复制文件夹操作 成功执行");
287}
288catch (Exception e)
289{
290System.out.println("复制整个文件夹内容操作出错");
291e.printStackTrace();
292}
293}
294/**
295* 移动文件到指定目录
296* @param oldPath String 如:c:/fqf.txt
297* @param newPath String 如:d:/fqf.txt
298*/
299public void moveFile(String oldPath, String newPath)
300{
301copyFile(oldPath, newPath);
302delFile(oldPath);
303}
304/**
305* 移动文件到指定目录
306* @param oldPath String 如:c:/fqf.txt
307* @param newPath String 如:d:/fqf.txt
308*/
309public void moveFolder(String oldPath, String newPath)
310{
311copyFolder(oldPath, newPath);
312delFolder(oldPath);
313}
314public static void main(String args[])
315{
316String aa,bb;
317boolean exitnow=false;
318System.out.println("使用此功能请按[1] 功能一:新建目录");
319System.out.println("使用此功能请按[2] 功能二:新建文件");
320System.out.println("使用此功能请按[3] 功能三:删除文件");
321System.out.println("使用此功能请按[4] 功能四:删除文件夹");
322System.out.println("使用此功能请按[5] 功能五:删除文件夹里面的所有文件");
323System.out.println("使用此功能请按[6] 功能六:复制文件");
324System.out.println("使用此功能请按[7] 功能七:复制文件夹的所有内容");
325System.out.println("使用此功能请按[8] 功能八:移动文件到指定目录");
326System.out.println("使用此功能请按[9] 功能九:移动文件夹到指定目录");
327System.out.println("使用此功能请按[10] 退出程序");
328while(!exitnow)
329{
330FileOperate fo=new FileOperate();
331try
332{
333BufferedReader Bin=new BufferedReader(new InputStreamReader(System.in));
334String a=Bin.readLine();
335int b=Integer.parseInt(a);
336switch(b)
337{
338case 1:System.out.println("你选择了功能一 请输入目录名");
339aa=Bin.readLine();
340fo.newFolder(aa);
341break;
342case 2:System.out.println("你选择了功能二 请输入文件名");
343aa=Bin.readLine();
344System.out.println("请输入在"+aa+"中的内容");
345bb=Bin.readLine();
346fo.newFile(aa,bb);
347break;
348case 3:System.out.println("你选择了功能三 请输入文件名");
349aa=Bin.readLine();
350fo.delFile(aa);
351break;
352case 4:System.out.println("你选择了功能四 请输入文件名");
353aa=Bin.readLine();
354fo.delFolder(aa);
355break;
356case 5:System.out.println("你选择了功能五 请输入文件名");
357aa=Bin.readLine();
358fo.delAllFile(aa);
359break;
360case 6:System.out.println("你选择了功能六 请输入文件名");
361aa=Bin.readLine();
362System.out.println("请输入目标文件名");
363bb=Bin.readLine();
364fo.copyFile(aa,bb);
365break;
366case 7:System.out.println("你选择了功能七 请输入源文件名");
367aa=Bin.readLine();
368System.out.println("请输入目标文件名");
369bb=Bin.readLine();
370fo.copyFolder(aa,bb);
371break;
372case 8:System.out.println("你选择了功能八 请输入源文件名");
373aa=Bin.readLine();
374System.out.println("请输入目标文件名");
375bb=Bin.readLine();
376fo.moveFile(aa,bb);
377break;
378case 9:System.out.println("你选择了功能九 请输入源文件名");
379aa=Bin.readLine();
380System.out.println("请输入目标文件名");
381bb=Bin.readLine();
382fo.moveFolder(aa,bb);
383break;
384case 10:exitnow=true;
385System.out.println("程序结束,请退出");
386break;
387default:System.out.println("输入错误.请输入1-10之间的数");
388}
389System.out.println("请重新选择功能");
390}
391catch(Exception e)
392{
393System.out.println("输入错误字符或程序出错");
394}
395}
396}
397}

地址:http://www.ibm.com/developerworks/cn/java/j-lo-javaio/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值