1、java读取txt文件内容java
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); } }
2、截取指定字符串中的某段字符数组
例如:字符串=“房估字(2014)第YPQD0006号”
网络
String str = "房估字(2014)第YPQD0006号"; String result = str.substring(str.indexOf("第")+1, str.indexOf("号"));
其中,substring函数有两个参数:函数
一、第一个参数是开始截取的字符位置。(从0开始)编码
二、第二个参数是结束字符的位置+1。(从0开始)spa
indexof函数的做用是查找该字符串中的某个字的位置,而且返回。code
扩展:substring这个函数也能够只写一个参数,就是起始字符位置。这样就会自动截取从开始到最后。blog
public class Test{ public static void main(String args[]){ String str = new String("0123456789"); System.out.println("返回值:" + str.substring(4); } }
结果为:456789 注意:结果包括4。字符串
其余示例:string
"hamburger".substring(3,8) returns "burge" "smiles".substring(0,5) returns "smile"
3、读取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();
4、对某一段字符串的修改
String str = "一我的至少拥有一个梦想,有一个理由去坚强。心若没有栖息的地方,到哪里都是在流浪。" if(str != null){
System.out.println(str.replace("一我的","一群人"));
}
结果为:一群人至少拥有一个梦想,有一个理由去坚强。心若没有栖息的地方,到哪里都是在流浪。
注:以上内容来自网络,简单整理记录。