大家好我一直在使用我的BufferedWriter问题。起初我只有1个缓冲写入器1显示为cc
,这与输出完美配合,但现在我已经尝试实现2我继续得到错误其他地方
Multiple markers at this line
- Syntax error, insert "}" to complete Statement
- Syntax error, insert "Finally" to complete
这是代码。错误从}else if (command.equals("action 2"))
行
if (selected) {
if (command.equals("action1")) {
BufferedWriter aa;
try {
File writerB = new File("output1.txt"); //set transaction-list.txt to be the destination file when writeTransactions is used
if (!writerB.exists()) {
writerB.createNewFile();
}
FileWriter bb = new FileWriter(writeBalance, true); //filewriter
aa = new BufferedWriter(bb); // bufferedwriter
BufferedWriter cc;
try {
int x=0;
File writerT = new File("output2.txt"); //set transaction-list.txt to be the destination file when writeTransactions is used
if (!writerT.exists()) {
writerT.createNewFile();
}
FileWriter dd = new FileWriter(writeTransactions, true); //filewriter
cc = new BufferedWriter(dd); // bufferedwriter
String newLine = System.getProperty("line.separator"); //creates a line separator which will be used with string newLine
if (n==0) {
bw.write(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now) + newLine);
wb.write(c);}
bw.close;
wb.close}
}else if (command.equals("action 2"))
答案 0 :(得分:1)
你没有妥善处理你的资源;一个人应该在finally
区块中关闭......
...但是,还有更好的方法是使用try-with-resources语句以及新的java.nio.file API:
final Path file1 = Paths.get("output1.txt");
final Path file2 = Paths.get("output2.txt");
try (
final BufferedWriter writer1 = Files.newBufferedWriter(file1, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
final BufferedWriter writer2 = Files.newBufferedWriter(file2, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
) {
// use writer1 and writer2 here.
// Note that BufferedWriter has a .newLine() method as well.
}
答案 1 :(得分:0)
在catch
之后,您未在try
之后进行catch
阻止。在finally
之后,try
或{{1}}块必需。
如前所述,强烈建议使用Java 7中引入的try-with-resources语句。