Groovy write to file (newline)

前端 未结 5 1528
你的背包
你的背包 2020-12-24 01:05

I created a small function that simply writes text to a file, but I am having issues making it write each piece of information to a new line. Can someone explain why it puts

相关标签:
5条回答
  • 2020-12-24 01:42

    Might be cleaner to use PrintWriter and its method println.
    Just make sure you close the writer when you're done

    0 讨论(0)
  • 2020-12-24 01:43

    As @Steven points out, a better way would be:

    public void writeToFile(def directory, def fileName, def extension, def infoList) {
      new File("$directory/$fileName$extension").withWriter { out ->
        infoList.each {
          out.println it
        }
      }
    }
    

    As this handles the line separator for you, and handles closing the writer as well

    (and doesn't open and close the file each time you write a line, which could be slow in your original version)

    0 讨论(0)
  • 2020-12-24 01:50

    I came across this question and inspired by other contributors. I need to append some content to a file once per line. Here is what I did.

    class Doh {
       def ln = System.getProperty('line.separator')
       File file //assume it's initialized 
    
       void append(String content) {
           file << "$content$ln"
       }
    }
    

    Pretty neat I think :)

    0 讨论(0)
  • 2020-12-24 01:50

    @Comment for ID:14. It's for me rather easier to write:

    out.append it
    

    instead of

    out.println it
    

    println did on my machine only write the first file of the ArrayList, with append I get the whole List written into the file.

    Kindly anyway for the quick-and-dirty-solution.

    0 讨论(0)
  • 2020-12-24 01:51

    It looks to me, like you're working in windows in which case a new line character in not simply \n but rather \r\n

    You can always get the correct new line character through System.getProperty("line.separator") for example.

    0 讨论(0)
提交回复
热议问题