簡體   English   中英

Java將多行字符串保存到文本文件

[英]Java save multiline string to text file

我是Java的新手,正在嘗試將多行字符串保存到文本文件中。

現在,它確實可以在我的應用程序中運行。 就像,如果我從應用程序中保存文件,然后從應用程序中將其打開,則會在行之間放置空格。 但是,如果我從應用程序中保存文件,然后在記事本中將其打開,則它們全部在一行上。

有沒有辦法讓它在所有程序上顯示多行? 這是我當前的代碼:

public static void saveFile(String contents) {

    // Get where the person wants to save the file
    JFileChooser fc = new JFileChooser();

    int rval = fc.showSaveDialog(fc);

        if(rval == JFileChooser.APPROVE_OPTION) {

            File file = fc.getSelectedFile();

            try {
                //File out_file = new File(file);
                BufferedWriter out = new BufferedWriter(new FileWriter(file));
                out.write(contents);
                out.flush();
                out.close();
            } catch(IOException e) {
                messageUtilities.errorMessage("There was an error saving your file. IOException was thrown.", "File Error");
            }
        }

        else {
            // Do nothing
            System.out.println("The user choose not to save anything");
        }
}

根據您構造字符串的方式,您可能只是遇到了行尾問題。 記事本不支持UNIX行尾(僅\\ n),僅支持Windows行尾(\\ n \\ r)。 請嘗試使用功能更強大的編輯器打開保存的文件,和/或確保您使用的平台行尾正確。 java的系統屬性(System.getProperty(“ line.separator”))將為您提供運行代碼的平台的正確行尾。

在構建要保存到文件中的字符串時,而不是為行尾顯式指定“ \\ n”或“ \\ n \\ r”(或在Mac的“ \\ r”上),您可以附加該值該系統屬性。

像這樣:

String eol = System.getProperty("line.separator");

... somewhere else in your code ...

String texttosave = "Here is a line of text." + eol;

... more code.. optionally adding lines of text .....
// call your save file method
saveFile(texttosave);

我的男朋友也遇到了同樣的問題,經過深思熟慮和研究,我什至找到了解決方案。

您可以使用ArrayList來放置TextArea的所有內容作為示例,並通過調用save來作為參數發送,因為編寫者剛剛編寫了字符串行,然后我們使用“ for”一行一行地最后編寫我們的ArrayList我們將在txt文件中使用TextArea內容。 如果沒有什么意義,對不起,我是google翻譯者,我不會說英語。

觀看Windows記事本,它並不總是跳行,而是全部顯示在一行中,請使用寫字板確定。


私人無效SaveActionPerformed(java.awt.event.ActionEvent evt){

    String NameFile = Name.getText();
    ArrayList< String > Text = new ArrayList< String >();

    Text.add(TextArea.getText());

    SaveFile(NameFile, Text);
} 

公共無效SaveFile(字符串名稱,ArrayList <String>消息){

    path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

    File file1 = new File(path);

    try {

        if (!file1.exists()) {

            file1.createNewFile();
        }


        File[] files = file1.listFiles();


        FileWriter fw = new FileWriter(file1, true);

        BufferedWriter bw = new BufferedWriter(fw);

        for (int i = 0; i < message.size(); i++) {

            bw.write(message.get(i));
            bw.newLine();
        }

        bw.close();
        fw.close();

        FileReader fr = new FileReader(file1);

        BufferedReader br = new BufferedReader(fr);

        fw = new FileWriter(file1, true);

        bw = new BufferedWriter(fw);

        while (br.ready()) {

            String line = br.readLine();

            System.out.println(line);

            bw.write(line);
            bw.newLine();

        }
        br.close();
        fr.close();

    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error in" + ex);        
}

是的,前面的答案提到了System.getProperty(“ line.seperator”)。

您的代碼未顯示如何創建String內容,但是由於您說過您是Java的新手,所以我想我提到在Java中串聯Strings不好,因為它創建了a。 如果您通過執行以下操作來構建字符串:

String contents = ""
contents = contents + "sometext" + "some more text\n"

然后考慮改用java.lang.StrinBuilder

StringBuilder strBuilder = new StringBuilder();
strBuilder.append("sometext").append("somre more text\n");
...
String contents = strBuilder.toString();

另一種選擇是流式傳輸您打算寫入文件的內容,而不是構建一個大字符串然后輸出。

您可以添加如下內容:

contents = contents.replaceAll("\\n","\\n\\r");

如果記事本無法正確顯示。 但是,您可能會遇到一個不同的問題:在每次保存/加載時,您將獲得多個\\ r字符。 然后,為了避免在加載時出現這種情況,您必須調用與上面相同的代碼,但參數要相反。 僅使文本正確顯示在記事本中,這確實是一個丑陋的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM