When you have to deal with text files, the following source code might come handy.

The class supports read and write operations for text files.

Version History

The following table lists versions and applied changes of soiurce code available below.

Version Date Description
0.0.1  2014-09-09 Initial publish.
0.0.2 2015-04-16

Minor changes to some methods to throw exceptions rather than handling exceptions themselves and just returning boolean results.

Changed the standard encoding to use a currents system default encoding instead of using utf-8 as a standard.

0.0.3 2015-09-21

Fixed a bug in method findNextLine causing the method to always return last line in the source file even if it does not match a handed pattern.

Source Code

Below is the source code as I am using it. Hope it helps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package de.consulting.bolte.io;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * This class provides basic functionality for reading and writing text files.
 
 * @author Alexander Bolte - Bolte Consulting (2015)
 *         (This email address is being protected from spambots. You need JavaScript enabled to view it.)
 */
public class MightyOfficeText {
 
	/**
	 * A constructor for creating an not parameterized instantiation of this
	 * class.
	 */
	public MightyOfficeText() {
		/**
		 * The standard encoding is set to the default encoding of the current
		 * operating system.
		 */
		standardEncoding = System.getProperty("file.encoding");
	}
 
	public MightyOfficeText(String encoding) {
		this.standardEncoding = encoding;
	}
 
	public void ignoreHeader(boolean isIgnore) {
		this.isIgnore = isIgnore;
	}
 
	/**
	 * Returns a constant representing the default encoding of a current
	 * operating system.
	 
	 * @return - Returns the standard encoding string used for encoding text
	 *         files while reading and writing.
	 */
	public String getStandardEncoding() {
		return standardEncoding;
	}
 
	/**
	 * Sets the standard encoding used by an instantiation of this class to a
	 * provided String.
	 
	 * @param standardEncoding
	 *            - a String providing the standardEncoding to set.
	 */
	public void setStandardEncoding(String standardEncoding) {
		this.standardEncoding = standardEncoding;
	}
 
	/**
	 * Reading a small text file. This function should only be used for text
	 * files, which you know to be small since it will be read into a
	 * StringBuilder as a whole. The StringBuilder will use the Systems standard
	 * line separator.
	 
	 * @param filePath
	 *            - a fully qualified file path including file name as well as
	 *            extension.
	 * @return a StringBuilder containing the text from file available under
	 *         given file path including line breaks.
	 * @throws FileNotFoundException
	 */
	public StringBuilder readSmallTextFile(String filePath)
			throws FileNotFoundException {
		StringBuilder ret = null;
 
		scanBigTextFile(filePath);
		if (myScan != null) {
			ret = new StringBuilder();
			// Ignore header row, if desired.
			if (this.scanHasNextLine() && this.isIgnore) {
				this.scanNextLine();
			}
			// Read file data.
			while (this.scanHasNextLine()) {
				ret.append(this.scanNextLine()
						+ System.getProperty("line.separator"));
			}
		}
 
		return ret;
	}
 
	/**
	 * Prepares a class global variable of type Scanner in order to walk through
	 * the file from the outside without having to know how to do it in detail.
	 
	 * @param filePath
	 *            - a fully qualified file path including file name as well as
	 *            extension.
	 * @throws FileNotFoundException
	 */
	public void scanBigTextFile(String filePath) throws FileNotFoundException {
		File myFile = null;
 
		myFile = new File(filePath);
		myScan = new Scanner(myFile, standardEncoding);
		// Ignore header row, if desired.
		if (this.scanHasNextLine() && this.isIgnore) {
			this.scanNextLine();
		}
	}
 
	/**
	 * Prepares the global scanner for running through a big text file. Steps
	 * included are as follows 1. reference the file 2. set the encoding of the
	 * scanner to the current standard encoding 3. set the standard delimiter as
	 * provided in the global scanner
	 
	 * @param filePath
	 *            - a fully qualified file path including file name as well as
	 *            extension.
	 * @param delimiter
	 *            - a regular expression, which serves as a delimiter for a line
	 *            within a referenced text file. Using this you can easily walk
	 *            through columns in a delimiter separated value file.
	 * @throws FileNotFoundException
	 */
	public void scanBigTextFile(String filePath, String delimiter)
			throws FileNotFoundException {
		File myFile = null;
 
		myFile = new File(filePath);
		myScan = new Scanner(myFile, standardEncoding);
		myScan.useDelimiter(delimiter);
		// Ignore header row, if desired.
		if (this.scanHasNextLine() && this.isIgnore) {
			this.scanNextLine();
		}
	}
 
	/**
	 * Checks, if the global scanner can be advanced to the next split sub
	 * string in a line. A sub string is defined by the delimiter determined in
	 * the global scanner.
	 
	 * @return Returns true, if the class global scanner has a next element
	 *         matching the given delimiter.
	 */
	public boolean scanHasNext() {
		boolean ret = false;
 
		ret = myScan.hasNext();
		return ret;
	}
 
	/**
	 
	 * @return Returns a String holding the next match of the given delimiter.
	 */
	public String scanNext() {
		String ret = "";
		if (myScan.hasNext()) {
			ret = myScan.next();
		}
		return ret;
	}
 
	/**
	 * Checks, if the global scanner can be advanced to a next line. If no more
	 * line is found in the referenced file, the method returns false.
	 
	 * @return - Returns true, if the Scanner has any more lines available in
	 *         referenced text file.
	 */
	public boolean scanHasNextLine() {
		boolean ret = false;
 
		if (myScan != null) {
			ret = myScan.hasNextLine();
		}
		return ret;
	}
 
	/**
	 * @return - Returns the next line from the Scanners position within a
	 *         referenced text file.
	 */
	public String scanNextLine() {
		String ret = "";
 
		if (this.scanHasNextLine()) {
			ret = myScan.nextLine();
		}
		return ret;
	}
 
	/**
	 * Sets the global regular expression for use in the global Scanner. The
	 * function compiles a globally available Pattern Object, which is used by
	 * Scanner objects to find its regular expression within text files. See
	 * also function findNextLine in this class.
	 
	 * @param regEx
	 *            - a regular expression, which should be searched for in a text
	 *            file.
	 */
	public void setScannerPattern(String regEx) {
		this.pattern = Pattern.compile(regEx);
	}
 
	public String getScannerPattern() {
		return this.pattern.pattern();
	}
 
	/**
	 
	 * @return
	 */
	public String getNextRecordExcludingInRecordLineBreack() {
		String aRecord = null;
		if (lastLine != null && this.myScan.hasNextLine()) {
			aRecord = lastLine;
		} else if (this.myScan.hasNextLine()) {
			aRecord = this.myScan.next();
		} else {
			aRecord = lastLine;
			lastLine = null;
		}
 
		// Move to next line matching a pattern.
		while (this.myScan.hasNextLine()
				&& !(this.pattern.matcher((lastLine = this.myScan.nextLine())))
						.find()) {
			aRecord = aRecord + lastLine;
		}
 
		return aRecord;
	}
 
	/**
	 * Searches the text files line starting from the current position of the
	 * global Scanner for a globally defined pattern. The Scanner is advanced
	 * until the pattern is matched in any line. Once a pattern is matched the
	 * Scanner stops and the line holding the match is returned. A pattern is
	 * holding a regular expression.
	 
	 * @param pattern
	 *            - a regular expression matching the strings you want to have
	 *            returned from a text file.
	 * @return - returns a match and advanced the scanners current position to
	 *         the next match, ignoring line breaks and delimiters. Returns
	 *         null, if no more match was found in input stream.
	 */
	public String findNextLine() {
		String ret = null;
		Matcher myMatch = null;
 
		if (this.myScan.hasNextLine()) {
			do {
				ret = this.myScan.nextLine();
				myMatch = this.pattern.matcher(ret);
				if (!myMatch.find()) {
					ret = null;
				}
			} while (ret == null && this.myScan.hasNextLine());
		}
 
		return ret;
	}
 
	/**
	 * Uses a global Scanner object to read next available line from a text file
	 * referenced by a global Scanner. The delimiter used to split a read line
	 * is the delimiter set in the global Scanner.
	 
	 * @return - Returns an ArrayList holding Strings, each item within the list
	 *         representing one column in a text files line.
	 */
	public ArrayList<String> scanNextLineToArrayList() {
		ArrayList<String> ret = new ArrayList<String>();
 
		Scanner scan = new Scanner(myScan.nextLine());
		scan.useDelimiter(myScan.delimiter());
		while (scan.hasNext()) {
			ret.add(scan.next());
		}
		scan.close();
		scan = null;
 
		return ret;
	}
 
	/**
	 * Creates a new text file for writing and opens a global BufferedWriter,
	 * which is referencing the newly created file. If a file is already
	 * existing under given file path it will be overwritten.
	 
	 * Used encoding is the systems encoding as defined per
	 * this.getStandardEncoding.
	 
	 * @param filePath
	 *            - a fully qualified file path including file name and file
	 *            extension.
	 
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException
	 */
	public void createTextFileForWriting(String filePath)
			throws FileNotFoundException, UnsupportedEncodingException {
 
		this.buffOut = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(filePath), this.getStandardEncoding()));
	}
 
	/**
	 * Opens an existing text file for appending data.
	 
	 * Used encoding is as defined as per this.getStandardEcoding.
	 
	 * @param filePath
	 *            a fully qualified file path including file extension.
	 
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 */
	public void openTextFileForWriting(String filePath)
			throws UnsupportedEncodingException, FileNotFoundException {
		this.buffOut = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(filePath, true),
				this.getStandardEncoding()));
	}
 
	/**
	 * Writes a new line into an before opened text file, referenced by the
	 * global BufferedWriter.
	 
	 * @param line
	 *            - a line of text to be written into a text file.
	 * @throws IOException
	 */
	public void writeLine(String line) throws IOException {
		this.buffOut.write(line);
		this.buffOut.newLine();
	}
 
	/**
	 * Closes the global BufferedWriter and sets it to null.
	 */
	public void closeTextFileForWriting() {
		try {
			this.buffOut.close();
			this.buffOut = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	/**
	 * Closes the class global Scanner and sets it to null.
	 */
	public void closeScanner() {
		myScan.close();
		myScan = null;
	}
 
	/**
	 * Global variables.
	 */
	private Scanner myScan = null;
	private BufferedWriter buffOut;
	private Pattern pattern;
	private String lastLine = null;
	private String standardEncoding = null;
	private boolean isIgnore;
}

Unit Test

Below a little unit test showing how to grab some lines matching patterns from text files.

Depending on your input file (see below for used sample) and the used pattern you will get null or a result String.

Encoding in this example is UTF-8. Has to be changed based on your input file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	...
    @Test
	public void testFindLines() throws FileNotFoundException {
		final String srcPath = "C:\\Users\\xxx\\Upload\\testFileUtf8.txt";
		final String regEx = "Bla";
		MightyOfficeText txt = new MightyOfficeText("UTF-8");
		String res = null;
 
		txt.scanBigTextFile(srcPath);
		txt.setScannerPattern(regEx);
		res = txt.findNextLine();
		txt.closeScanner();
 
		System.out.println(res);
	}
    ...

Source file sample

Haha
HuhuBla
Bla This is some test text.