【发布时间】:2014-02-14 09:06:59
【问题描述】:
仅供参考:我有另一个与此代码有关的问题,我已经问过了,我(完全)编辑了这个问题的问题,但没有得到任何答复。
AIM:我正在尝试读取文件(包含 HTML 的 .txt)并对内容进行排序。它确实创建了一个文本文件,并且完全为空。 我读过一些类似的情况,但我发现他们的错误是没有添加 out.flush() 或 out.close() 文件。
这是到目前为止的代码:
import java.io.*;
public class File {
public static void main(String[] args) throws IOException {
try {
String input = "SCCM.txt";
BufferedReader in = new BufferedReader(new FileReader(input));
String output = "output.txt";
BufferedWriter out = new BufferedWriter( new FileWriter( output ) );
String inputLine = "", s="windows";
String regex = " ";
while ((inputLine = in.readLine()) != null) {
if ( inputLine.contains(s) ) {
inputLine.split(regex);
out.append( inputLine );
out.newLine( );
}
in.close();
out.flush();
out.close();
}
}
catch(IOException e) {
System.out.println("Hi");
}
}
}
我要排序的内容:
<TR class="RowDark">
<TD width=0><A href="Report.asp?ReportID=100&sp=Service+Pack+1&os=Microsoft%28R%29+Windows%28R%29+Server+2003%2C+Enterprise+Edition"><IMG border=0 src="images/icolink3.gif" alt="Open the target" width=11 height=11></A></TD>
<TD class=SimpleTextSmall> Microsoft(R) Windows(R) Server 2003, Enterprise Edition </TD>
<TD class=SimpleTextSmall> Service Pack 1 </TD>
<TD class=SimpleTextSmall> 60 </TD>
</TR>
我想要的输出: Microsoft (R) Windows (R) Server 2003 , Enterprise Edition , Service Pack 1 , 60
我阅读的内容(供您参考): Java txt File from FileWriter is empty
更新:
import java.io.*;
公共类文件{
public static void main(String[] args) throws IOException {
String input = "SCCM.txt";
BufferedReader in = new BufferedReader(new FileReader(input));
String output = "output.txt";
BufferedWriter out = new BufferedWriter( new FileWriter( output ) );
try {
String inputLine = "", s="Windows";
String regex = " ";
while ((inputLine = in.readLine()) != null) {
if ( inputLine.contains(s) ) {
inputLine.split(regex);
out.write(inputLine);
out.newLine( );
}
}
}
catch(IOException e) {
System.out.println("Hi");
in.close();
out.flush();
out.close();
}
}
}
更新:
文件确实输出了(对帮助过的人表示爱意)
是这样的
<TD width=0><A href="Report.asp?ReportID=100&sp=Service+Pack+1&os=Microsoft%28R%29+Windows%28R%29+Server+2003%2C+Enterprise+Edition"><IMG border=0 src="images/icolink3.gif" alt="Open the target" width=11 height=11></A></TD>
<TD class=SimpleTextSmall> Microsoft(R) Windows(R) Server 2003, Enterprise Edition </TD>
有什么提示/提示/技巧可以让它变得可读吗?
【问题讨论】:
-
还要注意
String.contains()区分大小写。您的搜索字符串是“windows”,但您搜索的行包含“Windows”。 -
我尝试了提供的两个建议,但文件仍然是空的
-
您现在已搜索“Windows”(大写)并将您的 close() 语句移出 while 循环?
-
我给了代码的更新版本!是的,我遵循了这两个步骤! :)
-
@ToxicGlow 您需要将关闭语句放在 finally 块而不是异常块中,如下所示:)