Java读取txt文件信息并操作。

一、java读取txt文件内容

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
 
/**
 * @author 码农小江
 * H20121012.java
 * 2012-10-12下午11:40:21
 */
public class H20121012 {
    /**
     * 功能:Java读取txt文件的内容
     * 步骤:1:先获得文件句柄
     * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
     * 3:读取到输入流后,需要读取生成字节流
     * 4:一行一行的输出。readline()。
     * 备注:需要考虑的是异常情况
     * @param filePath
     */
    public static void readTxtFile(String filePath){
        try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                        System.out.println(lineTxt);
                    }
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
     
    }
     
    public static void main(String argv[]){
        String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
//      "res/";
        readTxtFile(filePath);
    }

}

 

二、截取指定字符串中的某段字符

例如:字符串=“房估字(2014)第YPQD0006号”

String str = "房估字(2014)第YPQD0006号";
String result = str.substring(str.indexOf("第")+1, str.indexOf("号"));

其中,substring函数有两个参数:

1、第一个参数是开始截取的字符位置。(从0开始)

2、第二个参数是结束字符的位置+1。(从0开始)

indexof函数的作用是查找该字符串中的某个字的位置,并且返回。

扩展:substring这个函数也可以只写一个参数,就是起始字符位置。这样就会自动截取从开始到最后。

public class Test{
    public static void main(String args[]){
        String str = new String("0123456789");
        
        System.out.println("返回值:" + str.substring(4);
    }
}

结果为:456789  注意:结果包括4。

其他示例:

"hamburger".substring(3,8) returns "burge"

"smiles".substring(0,5) returns "smile"

 

三、读取txt并获取某一部分字符串

某地址下的txt文件:list.txt

其内容:

test1=aa
test2=bb
test3=cc

可以每次读取一行,然后对单独对每行进行处理

File file = new File("D:\\list.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine())!= null){    //一次读取一行
  System.out.println(line);
  String[] tmp = line.split("=");    //根据'='将每行数据拆分成一个数组
  for(int i=0; i<tmp.length; i++){
    System.out.println("\t" + tmp[i]);    //tmp[1]就是你想要的信息,如:bb
  }
  if(line.endsWith("bb")){
      //判断本行是否以bb结束
    System.out.println("这是我想要的: " + tmp[1]);
  }
}
br.close();

 

 四、对某一段字符串的修改

String str = "一个人至少拥有一个梦想,有一个理由去坚强。心若没有栖息的地方,到哪里都是在流浪。"
if(str != null){
   System.out.println(str.replace("一个人","一群人"));
}

结果为:一群人至少拥有一个梦想,有一个理由去坚强。心若没有栖息的地方,到哪里都是在流浪。

 

注:以上内容来自网络,简单整理记录。

 

  

posted @ 2019-03-14 15:41  醉酒染青衣  阅读(3591)  评论(0编辑  收藏  举报