Hardcoded File Separator
ID |
java.hardcoded_file_separator |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability |
Description
Reports string literals containing hardcoded file path separators ("/" or "\\") used in string concatenation expressions that build file paths. Hardcoded separators break portability across operating systems.
Rationale
Different operating systems use different file path separators: Unix/macOS use /, Windows uses \. Hardcoding a separator makes the code non-portable:
File f = new File(dir + "/" + name); // Fails on Windows
File f = new File(dir + "\\" + name); // Fails on Unix
Remediation
Use java.io.File.separator, the two-argument File constructor, or java.nio.file.Path:
// Option 1: File.separator
File f = new File(dir + File.separator + name);
// Option 2: Two-argument constructor (preferred)
File f = new File(dir, name);
// Option 3: Path API
Path p = Path.of(dir, name);