在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java实现读取txt文件中的内容

2016-8-29 13:19| 发布者: zhangjf| 查看: 502| 评论: 0

摘要: 我们先来看个例子 import java.io.*; /*** Created by liguoqing on 2016/3/28.*/public class ReadTxtFile { public static void readTxt(String filePath) { try { File file = new File(filePath); if(f ...

我们先来看个例子

  1. import java.io.*;
  2. /**
  3. * Created by liguoqing on 2016/3/28.
  4. */
  5. public class ReadTxtFile {
  6. public static void readTxt(String filePath) {
  7. try {
  8. File file = new File(filePath);
  9. if(file.isFile() && file.exists()) {
  10. InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
  11. BufferedReader br = new BufferedReader(isr);
  12. String lineTxt = null;
  13. while ((lineTxt = br.readLine()) != null) {
  14. System.out.println(lineTxt);
  15. }
  16. br.close();
  17. } else {
  18. System.out.println("文件不存在!");
  19. }
  20. } catch (Exception e) {
  21. System.out.println("文件读取错误!");
  22. }
  23. }
  24. public static void main(String[] args) {
  25. String filePath = "D:\test\我.txt";
  26. readTxt(filePath);
  27. }
  28. }
复制代码

看完上面的例子,我们再来详细研究下

java读取txt文件内容。可以作如下理解:

首先获得一个文件句柄。File file = new File(); file即为文件句柄。两人之间连通电话网络了。接下来可以开始打电话了。

通过这条线路读取甲方的信息:new FileInputStream(file) 目前这个信息已经读进来内存当中了。接下来需要解读成乙方可以理解的东西

既然你使用了FileInputStream()。那么对应的需要使用InputStreamReader()这个方法进行解读刚才装进来内存当中的数据

解读完成后要输出呀。那当然要转换成IO可以识别的数据呀。那就需要调用字节码读取的方法BufferedReader()。同时使用bufferedReader()的readline()方法读取txt文件中的每一行数据哈。

  1. package com.campu;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.Reader;
  8. /**
  9. * @author 码农小江
  10. * H20121012.java
  11. * 2012-10-12下午11:40:21
  12. */
  13. public class H20121012 {
  14. /**
  15. * 功能:Java读取txt文件的内容
  16. * 步骤:1:先获得文件句柄
  17. * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
  18. * 3:读取到输入流后,需要读取生成字节流
  19. * 4:一行一行的输出。readline()。
  20. * 备注:需要考虑的是异常情况
  21. * @param filePath
  22. */
  23. public static void readTxtFile(String filePath){
  24. try {
  25. String encoding="GBK";
  26. File file=new File(filePath);
  27. if(file.isFile() && file.exists()){ //判断文件是否存在
  28. InputStreamReader read = new InputStreamReader(
  29. new FileInputStream(file),encoding);//考虑到编码格式
  30. BufferedReader bufferedReader = new BufferedReader(read);
  31. String lineTxt = null;
  32. while((lineTxt = bufferedReader.readLine()) != null){
  33. System.out.println(lineTxt);
  34. }
  35. read.close();
  36. }else{
  37. System.out.println("找不到指定的文件");
  38. }
  39. } catch (Exception e) {
  40. System.out.println("读取文件内容出错");
  41. e.printStackTrace();
  42. }
  43. }
  44. public static void main(String argv[]){
  45. String filePath = "L:\Apache\htdocs\res\20121012.txt";
  46. // "res/";
  47. readTxtFile(filePath);
  48. }
  49. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-6 22:02

Copyright 2015-2025 djqfx

返回顶部