Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Beware Platform-Dependent File Code

Problem

Chastened by the previous recipe, you now wish to write only platform-independent code.

Solution

Use readLine( ) and println( ). Never use \n by itself; use File.separator if you must.

Discussion

As mentioned in Section 9.10, if you just use readLine( ) and println( ), you won’t have to think about the line endings. But a particular problem, especially for recycled C programmers and their relatives, is using the \n character in text strings to mean a newline. What is particularly distressing about this code is that it will work -- sometimes -- usually on the developer’s own platform. But it will surely someday fail, on some other system.

// BadNewline.java
String myName;
public static void main(String argv[]) {
    BadNewline jack = new BadNewline("Jack Adolphus Schmidt, III");
    System.out.println(jack);
}
/**
 * DON'T DO THIS. THIS IS BAD CODE.
 */
public String toString(  ) {
    return "BadNewlineDemo@" + hashCode(  ) + "\n" + myName;
}

// The obvious Constructor is not shown for brevity; it's in the code

The real problem is not that it will fail on some platforms, though. What’s really wrong is that it mixes formatting and input/output, or tries to. Don’t mix line-based display with toString( ): avoid “multiline strings” output from toString( ) or any other string-returning method. If you need to write multiple strings, then say what you mean:

// GoodNewline.java String myName; public static void main(String argv[]) { GoodNewline jack = new GoodNewline("Jack ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata