x4nd3r
x4nd3r

Reputation: 900

Concatenate lines in a file

I have a number of data files which contain lines of contiguous character blocks, e.g.

thisisthefirstline
thisisthesecondline
thisisthethirdline

I am reading in each of these lines and concatenating them to create one long String which I then process. My question is, is there an elegant way to handle the concatenation of lines within a plaintext file?

Currently I am performing this task as follows:

BufferedReader br = new BufferedReader(new FileReader(sequence));
String line;
String sequence = "";
while ((line = br.readLine()) != null)
    sequence += line;
// do stuff with sequence here

Is there a way to achieve this using only the sequence container variable, and not the line temporary variable?

Upvotes: 0

Views: 2457

Answers (3)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

You can use an interesting quick way; use readAllLines (Java 7) and write:

List<String> lines = Files.readAllLines(Paths.get("fileName"), StandardCharsets.UTF_8);
String longString = Arrays.toString(lines.toArray()).replaceAll("\\[|\\]", "").replaceAll(", ","\t");

However, its not the best way to convert array to string.

I would use Guava package:

String longString = Joiner.on("\t").join(lines);

Upvotes: 1

x4nd3r
x4nd3r

Reputation: 900

I have ended up using the following loop to perform the necessary String concatenation:

String seq = "";
for (String line; (line = br.readLine()) != null; )
    seq += line;

Although this does not avoid the use of a temporary variable, I think it is preferable to the standard while-loop approach. Here, the scope of the temporary variable line is limited to the loop where file processing actually occurs.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280011

No, each call to BufferedReader#readLine() reads until a new line is found or the stream ends. Therefore, you can't call it twice: once for null and once to assign it to some variable. You need to have an temporary placeholder for comparing and using its value.

There's absolutely nothing wrong with what you are currently doing.

Upvotes: 2

Related Questions