java读取txt中指定长度的字符串并写出

比如说txt内容 this is a dataset TAGGGAAATTTGGGAAA 现在我需要读取TAGGG....这个字符串的3-7个字符 也就是要输出GGGAAAT 应该如何实现?

实现思路:先读取到txt文件中所有内容,之后通过特定条件,输出想要的字符串
可以通过BufferedReader 流的形式进行流缓存,之后通过readLine方法获取到缓存的内容。
BufferedReader bre = null;
try {
String file = "D:/test/test.txt";
bre = new BufferedReader(new FileReader(file));//此时获取到的bre就是整个文件的缓存流
while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环
{
//此处添加指定条件
if(str .length==12)
System.out.println(str);//原样输出读到的内容
};
备注: 流用完之后必须close掉,如上面的就应该是:bre.close(),否则bre流会一直存在,直到程序运行结束。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-07-17
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileOper {
public String readFile(String fileName) throws IOException {
File file = new File(fileName);
FileInputStream fis;
StringBuffer sb = new StringBuffer();

fis = new FileInputStream(file);
byte[] buf = new byte[1024];
int hasRead = 0;
while ((hasRead = fis.read(buf)) > 0) {
sb.append(new String(buf, 0, hasRead));
}
fis.close();
String str = sb.toString();
return str.substring(str.indexOf("TAG")+2, str.indexOf("TAG")+9);
}
public static void main(String[] args) throws IOException {
System.out.println(new FileOper().readFile("1.txt"));
}
}追问

您好,感谢你的回答。如果我的字符串TAG开头是 这三个字母的任意组合(也有可能是AAA GGT这样的 )代码应该如何修改呢?麻烦了 待会儿会提高选上 我的文件位置是D:\\111\\11.txt 谢谢!

追答

这个字符串的前面都是this is a dataset
这个么?

追问

字符串前面那段英文或许我可以手动删除一下吧 不用考虑那一段了 就直接处理字符串吧 开头不定 可能TAG TTT AAG各种组合都都可能 代码应该如何修改?

追答

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileOper {
public String readFile(String fileName) throws IOException {
File file = new File(fileName);
FileInputStream fis;
StringBuffer sb = new StringBuffer();

fis = new FileInputStream(file);
byte[] buf = new byte[1024];
int hasRead = 0;
while ((hasRead = fis.read(buf)) > 0) {
sb.append(new String(buf, 0, hasRead));
}
fis.close();
String str = sb.toString();
int left = str.indexOf("T");
if(str.indexOf("A")<left){
left = str.indexOf("A");
}
if(str.indexOf("G")<left){
left = str.indexOf("G");
}
return str.substring(left+2, left+9);
}
public static void main(String[] args) throws IOException {
System.out.println(new FileOper().readFile("D:\\111\\11.txt"));
}
}

本回答被提问者采纳
相似回答