Paths that work on Windows, macOS and Linux
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Showing steps for Windows. They are marked “On Windows” below.
A program that works on your Windows laptop may fail on a Linux server or a friend's Mac, only because of how it writes file names. Five small habits remove almost all of these bugs.
Backslash versus forward slash
Windows writes paths with a backslash \, such as C:\notes\test.txt. macOS and Linux use a forward slash /, such as /home/asha/notes/test.txt.
On Windows
This is a Windows view; names and sizes will differ on your computer. The folder is C:\Users\Priya\reports, written with backslashes. In a Java string, double each one: "C:\\Users\\Priya\\reports", or use /, or build it from parts.
PS C:\Users\Priya> cd reportsPS C:\Users\Priya> dirOutput Directory: C:\Users\Priya\reports Mode Length Name ---- ------ ---- -a---- 214 marks.csv
Example 1 · A Windows path in a string literal
public class EscapeDemo { public static void main(String[] args) { String broken = "C:\notes\test.txt"; String escaped = "C:\\notes\\test.txt"; String forward = "C:/notes/test.txt";
System.out.println("broken : " + broken.length() + " chars, has a new line? " + broken.contains("\n")); System.out.println("escaped: " + escaped.length() + " chars -> " + escaped); System.out.println("forward: " + forward.length() + " chars -> " + forward); }}broken : 15 chars, has a new line? true escaped: 17 chars -> C:\notes\test.txt forward: 17 chars -> C:/notes/test.txt
What this code does
- In
broken,\nbecame one new-line character and\tone tab, so the string is 2 characters shorter and is not a path at all. It compiles, which makes the bug easy to miss. - Doubling each backslash (
\\) gives a real backslash. Forward slashes avoid escaping and also work on Windows.
Example 2 · Mistake: an illegal escape stops the compiler
public class BadPathDemo { public static void main(String[] args) { String file = "D:\data\marks.txt"; System.out.println(file); }}BadPathDemo.java:3: error: illegal escape character
String file = "D:\data\marks.txt";
^
BadPathDemo.java:3: error: illegal escape character
String file = "D:\data\marks.txt";
^
2 errorsWhat this code does
\dand\mare not escape sequences Java knows, sojavacreports each one. This time you are lucky: the compiler catches it.- Fix:
"D:\\data\\marks.txt", or better,Path.of("data", "marks.txt")relative to the working directory.
In a Java string literal, \ starts an escape sequence: \n is a new line and \t is a tab. So "C:\notes\test.txt" silently becomes C:, a new line, otes, a tab and est.txt. A Windows path in a string needs every backslash doubled: "C:\\notes\\test.txt". Some letters, such as \d, are not valid escapes at all and stop the compiler. Java on Windows also accepts / in paths, so "C:/notes/test.txt" works there. The best habit avoids both problems: pass the names as parts, Path.of("notes", "test.txt"), and let Java add the separator.
Case-sensitive names on Linux
Linux treats Marks.csv and marks.csv as two different files. Windows, and macOS with its default settings, treat them as the same name: they keep the case you typed but ignore it when looking up a file.
Example 3 · Same name, different case
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class CaseDemo { public static void main(String[] args) throws IOException { Path saved = Path.of("Marks.csv"); Files.writeString(saved, "Asha,91");
Path typed = Path.of("marks.csv"); System.out.println("Exists as marks.csv? " + Files.exists(typed)); System.out.println("Paths equal? " + saved.equals(typed)); System.out.println("Names equal? " + saved.toString().equals(typed.toString()));
Files.delete(saved); }}Exists as marks.csv? true Paths equal? true Names equal? false
What this code does
- On Windows the lower-case lookup finds
Marks.csv, andPath.equalsignores case too. On Linuxmarks.csvdoes not exist and the two paths are not equal. - The plain strings differ on every system. If your code passes on Windows only because the case is ignored, it will fail on a Linux server.
So code that opens marks.csv when the file is really Marks.csv works on your laptop and fails on a Linux server with NoSuchFileException. On Windows, Path.equals even says the two paths are equal. The fix is a habit: always use the exact case of the real file name. Many teams keep file and folder names all lower case to make this easy.
Reserved names and characters on Windows
Windows bans some characters in file names: < > : " / \ | ? * and control characters. Java's Path.of("report 10:30.txt") throws InvalidPathException: Illegal char <:> on Windows, but works on Linux and macOS, which ban only / and the null character.
Example 4 · Making a user's text safe as a file name
import java.util.List;import java.util.Set;
public class SafeNameDemo { static final Set<String> RESERVED = Set.of("CON", "PRN", "AUX", "NUL");
static boolean isReserved(String name) { int dot = name.indexOf('.'); String base = (dot == -1 ? name : name.substring(0, dot)).toUpperCase(); return RESERVED.contains(base) || base.matches("(COM|LPT)[1-9]"); }
static String safeFileName(String text) { String name = text.replaceAll("[<>:\"/\\\\|?*]", "-"); name = name.replaceAll("[. ]+$", ""); if (name.isEmpty()) { name = "untitled"; } if (isReserved(name)) { name = "_" + name; } return name; }
public static void main(String[] args) { List<String> titles = List.of("Fest report 10:30", "Q&A: what next?", "con", "Aux.txt", "marks*final", "notes. ", "Hackathon/Day 1"); for (String t : titles) { System.out.println("[" + t + "] -> [" + safeFileName(t) + "]"); } }}[Fest report 10:30] -> [Fest report 10-30] [Q&A: what next?] -> [Q&A- what next-] [con] -> [_con] [Aux.txt] -> [_Aux.txt] [marks*final] -> [marks-final] [notes. ] -> [notes] [Hackathon/Day 1] -> [Hackathon-Day 1]
What this code does
- The regular expression lists every character Windows bans;
\\\\in the Java string is one backslash inside the pattern. Each banned character becomes-, and dots or spaces at the end are removed. - Reserved device names are checked on the part before the first dot, ignoring case, so
conandAux.txtboth get a_in front. A name built this way is legal on Windows, macOS and Linux.
Windows also reserves some device names: CON, PRN, AUX, NUL, COM1 to COM9 and LPT1 to LPT9, in any case and even with an extension, such as con.txt. Creating a file with one of these names fails or does something strange. A name may also not end with a space or a dot. When a file name comes from user input, such as a fest event title or a student's name, clean it first so it is legal on every system.
user.home and building paths from parts
user.home is the system property that holds the current user's home folder: C:\Users\Asha on Windows, /Users/asha on macOS, /home/asha on Linux. It is the right starting point for files that belong to the user, such as a settings folder.
Example 5 · Paths from user.home and parts
import java.nio.file.FileSystems;import java.nio.file.Path;
public class HomeDemo { public static void main(String[] args) { String home = System.getProperty("user.home"); Path report = Path.of(home, "Documents", "marksheet.pdf"); Path settings = Path.of(home, ".marks-app", "settings.properties");
System.out.println("Home folder : " + home); System.out.println("Report : " + report); System.out.println("Settings : " + settings.getFileName()); System.out.println("Separator : " + FileSystems.getDefault().getSeparator()); System.out.println("Inside home? " + report.startsWith(Path.of(home))); }}Home folder : C:\Users\Asha Report : C:\Users\Asha\Documents\marksheet.pdf Settings : settings.properties Separator : \ Inside home? true
What this code does
user.homegives the right home folder for whoever runs the program, on any system.Path.ofadds the separator between the parts.- A folder name starting with a dot, such as
.marks-app, is the usual place for an app's own settings. The separator is printed only to show it; the code never needs to type it.
Build the rest from parts: Path.of(System.getProperty("user.home"), "Documents", "marksheet.pdf"). If you need the separator as text, ask Java with FileSystems.getDefault().getSeparator() (or File.separator); never type it.
Hardcoded drive letters as a trap
A hardcoded path is one typed straight into the code, like "C:\\Users\\Ravi\\Desktop\\marks.csv". It works only on Ravi's laptop: another student has a different user name, a college lab may use drive D:, and Linux has no drive letters at all.
Example 6 · A hardcoded path versus a configurable one
import java.nio.file.Path;
public class DriveLetterDemo { static Path inputFile(String[] args) { if (args.length > 0) { return Path.of(args[0]); } return Path.of("data", "marks.csv"); }
public static void main(String[] args) { Path hard = Path.of("C:\\Users\\Ravi\\Desktop\\marks.csv"); System.out.println("Hard-coded absolute? " + hard.isAbsolute()); System.out.println("Hard-coded names : " + hard.getNameCount());
Path input = inputFile(args); System.out.println("Configurable file : " + input.getFileName()); System.out.println("Configurable names : " + input.getNameCount()); }}Hard-coded absolute? true Hard-coded names : 4 Configurable file : marks.csv Configurable names : 2
What this code does
- On Windows the hardcoded path has a root and four names. On Linux the backslashes are ordinary characters, so the whole string is one relative name and the file is never found.
inputFileuses the first program argument when there is one (java DriveLetterDemo D:/exam/marks.csv) and a relative default otherwise, so the same code runs on every computer.
On Linux that string is not even absolute; it is one strange relative file name full of backslashes.
Instead, take the location from outside the code: a program argument, a settings file, user.home, or a path relative to the working directory. Keep one sensible default for when nothing is given.
Next step
Check your understanding
12 quick questions