我有一个程序,我在其中使用 while 循环将打印到控制台和 html 文件。然而,即使它打印到控制台,程序也只会将最后一行打印到 html 文件。这是我的循环的代码,它应该打印从文本文件中提取的第 9 到第 16 行的信息。
//read the txt file
Path objPath = Paths.get("dirsize.txt");
if (Files.exists(objPath))
{
File objFile = objPath.toFile();
try(BufferedReader in = new BufferedReader(
new FileReader(objFile)))
{
String line = in.readLine();
int lineNum = 1;
//extract the month
String monthSubstring = line.substring(25,27);
month = Integer.parseInt(monthSubstring) -1 ;
//extact the year
String yearSubstring = line.substring(31,35);
year = (Integer.parseInt(yearSubstring));
//extract the date
String daySubstring = line.substring(28,30);
day = Integer.parseInt(daySubstring);
PrintWriter out = new PrintWriter (new BufferedWriter(new FileWriter("Output.html")));
while(line != null)
{
line = in.readLine();
lineNum ++;
if (lineNum == 3)
{
//extract the hour
String hourSubstring = line.substring(21,23);
hour = Integer.parseInt(hourSubstring);
//extract the minute
String minuteSubstring = line.substring(24,26);
minute = Integer.parseInt(minuteSubstring);
//extract the second
String secondSubstring = line.substring(27,29);
second= Integer.parseInt(secondSubstring);
}
if(lineNum ==5)
{
//Extract the branch
strBranch = line.substring(22, 27);
}
if (lineNum == 6)
{
//Extract the computer
strCPU = line.substring(26,32);
}
if (lineNum >= 9 && lineNum <= 16)
{
//call the MyDirectory methods to get the files name,size and number of files
MyDirectory directory = new MyDirectory(line);
fileName = directory.getName();
fileSize = directory.getsize();
fileNum = directory.getNum();
//create the dteDate calender
GregorianCalendar dteDate = new GregorianCalendar(year, month, day, hour, minute, second);
//fromat the date
SimpleDateFormat strDate = new SimpleDateFormat("MMM dd, yyyy h:m");
//Write the data to the file
out.println((strBranch + "; " +
strCPU + "; " +
strDate.format(dteDate.getTime())) + "; " +
fileName + "; " +
fileSize + "; " +
fileNum);
//create the necessary output for the console
System.out.println((strBranch + "; " +
strCPU + "; " +
strDate.format(dteDate.getTime())) + "; " +
fileName + "; " +
fileSize + "; " +
fileNum);
}
out.flush();
}
}
//catch any IOExceptions and print out e
catch (IOException e)
{
System.out.println(e);
}
}
编辑:通过答案中发布的建议,我现在有了所有内容的输出,但我很难对其进行格式化,html 文件包含所有行,没有空格我尝试在输出末尾使用“\n”,然后是我的代码无法编译,因为它说不允许空值,当它不允许我在打印方法的末尾放置“\n”时,有人知道如何将其格式化为行吗?
我不确定这是太多代码还是不足以解决问题,如果我应该在我的帖子中添加任何内容或删除任何内容,请告诉我。