[英]How to write String from variable to text file
我的目標是從文本文件中讀取行,檢查它們是否是回文,然后將它們寫入完全不同的文件。
現在,據我所見,問題在於 if 語句塊,我成功檢查了回文,但似乎無法將它們寫入另一個文件,因為它們存儲在變量中。
當我使用 BufferedWriter 寫入方法並將參數設置為帶引號的實際字符串時,一切正常。
我該如何解決這個問題?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
public class Zadatak14 {
public static void main(String[] args) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader("C:\\Users\\Luka\\Documents\\NetBeansProjects\\CS101-DZ14-14\\src\\zadatak14\\ulaz.txt"));
String line;
while ((line = br.readLine()) != null) {
String palindrome = new StringBuilder(line).reverse().toString();
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Luka\\Documents\\NetBeansProjects\\CS101-DZ14-14\\izlaz.txt"));
if (line.contains(palindrome)) {
System.out.println(line);
bw.write(line);
}
bw.close();
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("Greska");
} catch (IOException ex) {
System.out.println("Greska");
}
}
}
BufferedWriter bw = new BufferedWriter
您正在為 input 中的每一行創建一個新作家,這肯定是您不想要的。 在打開閱讀器之后,將作者的創作移到頂部。
br.close();
不是你怎么做的。 這就是你這樣做的方式:
try (BufferedWriter bw = new BufferedWriter(new FileWriter("...."))) {
// code here
}
// no matter how you get out of this code, the file is closed.
您使用上述方法執行此操作的原因是,如果您從塊中return
,則如果發生異常,則不會調用bw.close()
。 使用 try 構造,當代碼從塊中退出時,stream 將關閉,無論它如何執行。
} catch (FileNotFoundException e) {
System.out.println("Greska");
不是你怎么做的——異常包含很多有用的信息(至少有 4 件事,對於某些特定類型的異常更多:類型、消息、堆棧跟蹤、原因),你把它全部扔進了垃圾箱。 將有關問題的信息扔進垃圾箱是個壞主意。 不。 正確的做法是將throws Exception
添加到您的public static void main(String[] args)
方法中,然后您根本不需要捕獲。 如果必須,如果您沒有處理問題的好方法,則 catch 塊的正確主體是throw new RuntimeException("Uncaught", e);
. 這會保留所有信息,並且不會導致必須捕獲異常的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.