Here you can find the source of toURI(final java.io.File file, final StringBuilder builder)
Parameter | Description |
---|---|
file | The file to get a URI for. |
builder | A StringBuilder to help build the URI path. |
public static URI toURI(final java.io.File file, final StringBuilder builder)
//package com.java2s; import java.net.URI; import java.net.URISyntaxException; public class Main { private static final char FORWARD_SLASH = '/'; /**/* w ww . j av a 2 s .c om*/ * A method to return a file URI from a file, without creating lots of char[] garbage. * <p> * The method in File.toURI() creates a lot of char[] garbage as it appends slashes * and doesn't use a single stringbuilder. This method also allows us to pass in * an external string builder, so we can re-use an existing one. * * @param file The file to get a URI for. * @param builder A StringBuilder to help build the URI path. * @return A URI for the file. */ //CHECKSTYLE:OFF Too complex public static URI toURI(final java.io.File file, final StringBuilder builder) { java.io.File absoluteFile = file.getAbsoluteFile(); //Allow for Mockito tests where the previous assignment returns a null reference if (absoluteFile == null) { absoluteFile = new java.io.File(file.getAbsolutePath()); } final String path = absoluteFile.getPath(); final int length = path.length(); final char separator = java.io.File.separatorChar; // check how many start slashes we need. int numStartSlashes = 0; if (path.charAt(0) != separator) { numStartSlashes = 1; } else if (path.charAt(1) == separator) { numStartSlashes = 2; } // reset the builder to the start: builder.setLength(0); // do URI forward slashes for (int startSlashNum = 0; startSlashNum < numStartSlashes; startSlashNum++) { builder.append(FORWARD_SLASH); } // append path (transforming separators to forward slashes if necessary): if (separator == FORWARD_SLASH) { builder.append(path); } else { for (int charIndex = 0; charIndex < length; charIndex++) { final char theChar = path.charAt(charIndex); if (theChar == separator) { builder.append(FORWARD_SLASH); } else { builder.append(theChar); } } } // ensure we have a closing slash if the file is a directory: if (path.charAt(path.length() - 1) != separator && absoluteFile.isDirectory()) { builder.append(FORWARD_SLASH); } URI uri = null; try { uri = new URI("file", null, builder.toString(), null); } catch (URISyntaxException e) { // ignore - should never happen. } //CHECKSTYLE:ON return uri; } }