将堆栈中的每个元素打印到文本文件中的新行

时间:2012-01-29 22:11:23

标签: java string-formatting

我似乎无法将堆栈的每个字符串元素打印到新行。我希望能够使用另一个一次读取一行的方法从此文本文件中检索数据。我完成了那个方法。

public Save(Stack<String> names, String fileName)
{
    try
    {
        File Test = new File("" + fileName + ".txt");
        FileWriter out = new FileWriter(Test);

        while (names.empty() == false)
        {
            String output = names.pop();
            out.write(output);
        }
        out.close();
        VALID_SAVE = true;
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
} 

2 个答案:

答案 0 :(得分:1)

只需在每个out()之后添加换行符:

String output = names.pop();
out.write(output);
out.write("\n");

请:

while(!names.empty())

此外,由于FileNotFoundExceptionIOException的子类,并且异常处理相同,因此第一个catch子句是多余的。

答案 1 :(得分:0)

使用系统属性,它是独立于OS的行分隔符out.write(System.getProperty(“line.separator”))

相关问题