无法写入文件Scanner try / catch Java

时间:2015-03-03 14:45:19

标签: java loops output

当我运行此程序时,它意味着写入文本文件,文本文件与我的项目文件夹位于同一目录中。

try
{                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
Scanner inFile = new Scanner(new File ("details.txt"));
while(inFile.hasNext())
{
String line = inFile.nextLine(); //reads the line of text
Scanner del = new Scanner(line).useDelimiter("#"); //scanner class to delimit
String name = del.next();
String gender = del.next();
int age = del.nextInt();
double amount = del.nextDouble();
txaDisplay.append(name+"\t"+gender+"\t"+age+"\t"+amount+"\n");
del.close();
}
inFile.close();//end try
}
catch(FileNotFoundException f)
    {
    txaDisplay.append("File Not Found");
    System.exit(0);}
}                                        


public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new yest().setVisible(true);
        }
    });}

1 个答案:

答案 0 :(得分:1)

您需要实际写入该文件。这是我给新文件输出人员的一个例子。这使用FileWriter输出流。注意Data这里是ArrayList

public static void WriteFile(File file)
{
    System.out.println("Writing to file");
    //Use a FileWriter to output to file
    FileWriter oFile = null;
    try
    {
        oFile = new FileWriter(file, false); //Set to true if you don't want to overwrite existing contents in file

        // Begin writing to file... line by line
        for (String line : Data)
            oFile.write(line + System.getProperty("line.separator")); //Since notepad doesn't display newline characters (\n) use this
                                                                      //If using another text document viewer then just use + "\n"
        //Flush and close output stream
        oFile.flush();
        oFile.close();
    } catch (IOException e)
    {
        // Handle it!
        e.printStackTrace();
    }
}