Java 读取文件直到某个字符(BufferedReader)
以下是我的代码,它不起作用:Java 读取文件直到某个字符(BufferedReader),java,bufferedreader,Java,Bufferedreader,以下是我的代码,它不起作用: try { while ((line1 = br.readLine()).substring(6).equals(name)) { text = text + line1; //text = text + '\n'; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
try
{
while ((line1 = br.readLine()).substring(6).equals(name))
{
text = text + line1;
//text = text + '\n';
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
我试图做的是从文本文件中读取文本:
Name: Thailand.jpg.
Brief: This is Pattaya
Info: Nice city you know
Name: Austria.jpg
Brief: This is Austria
Info: Schwarzenegger was born here
现在我只想设置“这是奥地利”文本。但是不能
谢谢大家! 首先,我不知道你在这里要做什么@Rod_Algonquin也问了我一个问题。
你只想从文件中获取字符串“This is Austria?”
,但你没有对此发表任何评论
假设你要做类似的事情,你可以尝试如下
try {
BufferedReader br=new BufferedReader(
new FileReader(new File("/home/ruchira/Test.txt")));
String line;
String text = "";
try {
while ((line=br.readLine())!=null){
if(line.contains("Austria.jpg")){
String line1=br.readLine();
if(line1!=null){
text=text+line1.split(": ")[1];
}
}
}
System.out.println(text);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
您的子字符串索引错误。请重新计算一下。此外,还必须检查空指针条件。应将while循环条件更改为:
try
{
while((line1=br.readLine())!=null && line1.substring(8).equals(name))
{
text = text + line1;
//text = text + '\n';
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
在计算索引时,还应考虑空格。因此,您所需的子字符串索引变为8而不是6。因此您只想从文件中获取字符串“this is Austria”?这一行
而((line1=br.readLine()).substring(6).equals(name)){
是一团乱。分离成可读的逻辑。还有name
是什么?为什么子字符串(6)
?我的名字是奥地利。我需要奥地利的文本。那么你的问题是什么?注意,在对其执行任何其他操作之前,你需要测试readLine()
的null结果。此代码将在文件末尾抛出NullPointerException
。这是我想要的。谢谢!!!@NurgulAlshyn欢迎你