【问题标题】:Java save multiline string to text fileJava将多行字符串保存到文本文件
【发布时间】:2011-03-09 23:29:54
【问题描述】:

我是 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");
        }
}

【问题讨论】:

    标签: java file text save multiline


    【解决方案1】:

    根据您构建字符串的方式,您可能会遇到行尾问题。记事本不支持 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);
    

    【讨论】:

    • 写字板在这种情况下将是一个“更强大的编辑器”。您还可以使用 unix2dos 之类的程序来更改行尾,以便记事本识别它们。
    • 好的。我真的不知道如何应用它。我怎样才能让它使用正确的行分隔符?
    • Notepad++ 是我首选的精简版、非侵入性代码/数据编辑器。
    【解决方案2】:

    是的,因为前面的答案提到了 System.getProperty("line.seperator")。

    您的代码没有显示您是如何创建字符串内容的,但是既然您说您是 java 新手,我想我会提到在 java 中连接字符串并不好,因为它创建了一个。如果您通过这样做来构建字符串:

    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();
    

    另一种选择是将您计划写入的内容流式传输到文件中,而不是构建一个大字符串然后输出。

    【讨论】:

    • 我正在从文本区域获取字符串。我正在制作一个类似于记事本的程序。
    【解决方案3】:

    您可以添加如下内容:

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

    如果记事本无法正确显示。但是,您可能会遇到不同的问题:在每次保存/加载时,您将获得多个 \r 字符。然后为避免在加载时出现这种情况,您必须调用上面相同的代码,但参数相反。这真的是一个丑陋的解决方案,只是为了让文本在记事本中正确显示。

    【讨论】:

      【解决方案4】:

      我的男朋友也遇到了同样的问题,经过深思熟虑,我什至找到了解决方案。

      例如可以用ArrayList把TextArea的所有内容都放上来,调用save作为参数发送,因为作者只是写了string行,那么我们用“for”一行一行的写我们的ArrayList最后我们将内容TextArea在txt文件中。 如果有什么不明白的地方,我很抱歉谷歌翻译和我不会说英语。

      注意Windows记事本,它不会总是跳行,并且显示在一行中,使用写字板可以。


      private void SaveActionPerformed(java.awt.event.ActionEvent evt) {

          String NameFile = Name.getText();
          ArrayList< String > Text = new ArrayList< String >();
      
          Text.add(TextArea.getText());
      
          SaveFile(NameFile, Text);
      } 
      

      public void SaveFile(String name, ArrayList message) {

          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);        
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-06
        • 2021-08-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多