Skip to content

Instantly share code, notes, and snippets.

@alibitek
Created June 7, 2014 15:20
Show Gist options
  • Save alibitek/3b6266bc5d24ddaeda04 to your computer and use it in GitHub Desktop.
Save alibitek/3b6266bc5d24ddaeda04 to your computer and use it in GitHub Desktop.
Normalize white space in filepath
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestWhiteSpace {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/home/alex/Music/./Alexander Blu/Alexander_Blu_-_Electro_maniac.mp3");
System.out.println("Absolute path: " + path.toAbsolutePath());
System.out.println("URI: " + path.toUri());
System.out.println("Normalized Path: " + path.normalize());
System.out.println("Normalized URI: " + path.normalize().toUri());
try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(path.toFile()))) {
byte[] data = new byte[(int) path.toFile().length()];
int bytesRead = br.read(data);
System.out.println("Bytes read: " + bytesRead);
String encodedData = new String(data, Charset.defaultCharset());
System.out.println("Encoded data: " + encodedData);
}
}
}
/* Output:
Absolute path: /home/alex/Music/./Alexander Blu/Alexander_Blu_-_Electro_maniac.mp3
URI: file:///home/alex/Music/./Alexander%20Blu/Alexander_Blu_-_Electro_maniac.mp3
Normalized Path: /home/alex/Music/Alexander Blu/Alexander_Blu_-_Electro_maniac.mp3
Normalized URI: file:///home/alex/Music/Alexander%20Blu/Alexander_Blu_-_Electro_maniac.mp3 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment