From 07809fc12fa2e66cd8e7ceadde350b4d2281ea43 Mon Sep 17 00:00:00 2001 From: Kohsuke Kawaguchi Date: Thu, 16 Oct 2014 11:16:40 -0700 Subject: [PATCH] Added a convenience method --- core/src/main/java/hudson/util/TextFile.java | 33 +++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/hudson/util/TextFile.java b/core/src/main/java/hudson/util/TextFile.java index f010f12e1a..466830fc96 100644 --- a/core/src/main/java/hudson/util/TextFile.java +++ b/core/src/main/java/hudson/util/TextFile.java @@ -23,6 +23,8 @@ */ package hudson.util; +import com.google.common.collect.*; + import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.File; @@ -34,8 +36,8 @@ import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.Reader; import java.io.StringWriter; -import java.nio.*; import java.nio.charset.Charset; +import java.util.Iterator; /** * Represents a text file. @@ -76,6 +78,35 @@ public class TextFile { return out.toString(); } + /** + * Parse text file line by line. + */ + public Iterable lines() { + return new Iterable() { + @Override + public Iterator iterator() { + try { + final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); + + return new AbstractIterator() { + @Override + protected String computeNext() { + try { + String r = in.readLine(); + if (r==null) in.close(); + return r; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + }; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + }; + } + /** * Overwrites the file by the given string. */