【发布时间】:2017-06-28 16:26:14
【问题描述】:
所以我在这里遇到了一些麻烦。我需要能够将我的输出写入文件,并让它只包含代码中指定的关键字。此代码没有向文件写入任何内容,它只会打开另一个框供用户输入。我如何让它在用户输入文件名后关闭输入框,让它将输出写入文件,并让输出显示在编译器中?谢谢!
import java.util.*;
import java.io.*;
public class Classname {
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File( filename);
String textLine = null; // Null
String outLine = ""; // Null
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
try
{
// assigns the file to a filereader object..this will throw an error if
the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes
wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.printf("%s\n",outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it
will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will
throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
【问题讨论】:
-
在寻求免费帮助时,至少要花时间正确格式化您的代码。
-
这会让你更快乐吗?
-
伙计们,我仍然需要帮助。