Java Code Examples for java.io.File.toURI()

The following are Jave code examples for showing how to use toURI() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: litiengine   File: CompressionUtilities.java   View Source Code Vote up 6 votes
public static void zip(File directory, final File zipfile) throws IOException {
  final URI base = directory.toURI();
  final Deque<File> queue = new LinkedList<>();
  queue.push(directory);
  try (final OutputStream out = new FileOutputStream(zipfile)) {
    final ZipOutputStream zout = new ZipOutputStream(out);
    while (!queue.isEmpty()) {
      directory = queue.pop();
      for (final File kid : directory.listFiles()) {
        String name = base.relativize(kid.toURI()).getPath();
        if (kid.isDirectory()) {
          queue.push(kid);
          name = name.endsWith("/") ? name : name + "/";
          zout.putNextEntry(new ZipEntry(name));
        } else {
          zout.putNextEntry(new ZipEntry(name));
          StreamUtilities.copy(kid, zout);
          zout.closeEntry();
        }
      }
    }
  }
}
 
Example 2
Project: n4js   File: TargetPlatformInstallLocationProvider.java   View Source Code Vote up 6 votes
/**
 * Returns with the URI pointing to the local git repository root location for storing and retrieving N4JS
 * definition files for the npm installation process.
 *
 * @return the URI pointing to the local git repository location for the N4JSD files in the file system.
 */
default URI getTargetPlatformLocalGitRepositoryLocation() {
	if (null == getTargetPlatformInstallLocation()) {
		final String message = "Target platform install location was not specified.";
		final NullPointerException exception = new NullPointerException(message);
		LOGGER.error(message, exception);
		exception.printStackTrace(); // This if for the HLC as it swallows the actual stack trace.
		throw exception;
	}
	final File installLocation = new File(getTargetPlatformInstallLocation());
	checkState(installLocation.isDirectory(), "Cannot locate target platform install location: " + installLocation);
	// The local git repository should be a sibling folder of the install location.
	File parentFile = installLocation.getParentFile();
	if (null == parentFile || !parentFile.exists() || !parentFile.isDirectory()) {
		LOGGER.warn("Cannot get parent folder of the target platform install location: " + parentFile + ".");
		LOGGER.warn("Falling back to install location: " + installLocation + ".");
		parentFile = installLocation;
	}
	final File gitRoot = new File(parentFile, getGitRepositoryName());
	if (!gitRoot.exists()) {
		checkState(gitRoot.mkdir(), "Error while creating local git repository folder for target platform.");
	}
	checkState(gitRoot.isDirectory(),
			"Cannot locate local git repository folder in target platform install location.");
	return gitRoot.toURI();
}
 
Example 3
Project: circus-train   File: SimpleCopyListingTest.java   View Source Code Vote up 6 votes
@Test
public void failOnCloseError() throws IOException {
  File inFile = File.createTempFile("TestCopyListingIn", null);
  inFile.deleteOnExit();
  File outFile = File.createTempFile("TestCopyListingOut", null);
  outFile.deleteOnExit();
  Path source = new Path(inFile.toURI());

  Exception expectedEx = new IOException("boom");
  SequenceFile.Writer writer = mock(SequenceFile.Writer.class);
  doThrow(expectedEx).when(writer).close();

  SimpleCopyListing listing = new SimpleCopyListing(CONFIG, CREDENTIALS);
  Exception actualEx = null;
  try {
    listing.doBuildListing(writer, options(source, outFile.toURI()));
  } catch (Exception e) {
    actualEx = e;
  }
  Assert.assertNotNull("close writer didn't fail", actualEx);
  Assert.assertEquals(expectedEx, actualEx);
}
 
Example 4
Project: hadoop   File: TestCopyListing.java   View Source Code Vote up 6 votes
@Test
public void testFailOnCloseError() throws IOException {
  File inFile = File.createTempFile("TestCopyListingIn", null);
  inFile.deleteOnExit();
  File outFile = File.createTempFile("TestCopyListingOut", null);
  outFile.deleteOnExit();
  List<Path> srcs = new ArrayList<Path>();
  srcs.add(new Path(inFile.toURI()));
  
  Exception expectedEx = new IOException("boom");
  SequenceFile.Writer writer = mock(SequenceFile.Writer.class);
  doThrow(expectedEx).when(writer).close();
  
  SimpleCopyListing listing = new SimpleCopyListing(getConf(), CREDENTIALS);
  DistCpOptions options = new DistCpOptions(srcs, new Path(outFile.toURI()));
  Exception actualEx = null;
  try {
    listing.doBuildListing(writer, options);
  } catch (Exception e) {
    actualEx = e;
  }
  Assert.assertNotNull("close writer didn't fail", actualEx);
  Assert.assertEquals(expectedEx, actualEx);
}
 
Example 5
Project: openjdk-jdk10   File: Sibling.java   View Source Code Vote up 6 votes
public static void main(String... args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        JavaFileObject sibling =
            fm.getJavaFileObjectsFromFiles(Arrays.asList(new File("Test.java")))
            .iterator().next();
        JavaFileObject classFile =  fm.getJavaFileForOutput(CLASS_OUTPUT,
                                                            "foo.bar.baz.Test",
                                                            CLASS,
                                                            sibling);
        File file = new File("Test.class").getAbsoluteFile();
        if (!classFile.toUri().equals(file.toURI()))
            throw new AssertionError("Expected " + file.toURI() + ", got " +
                                     classFile.toUri());
    }
}
 
Example 6
Project: openjdk-jdk10   File: APITest.java   View Source Code Vote up 5 votes
protected void checkFiles(File dir, Set<String> expectFiles) {
    Set<File> files = new HashSet<File>();
    listFiles(dir, files);
    Set<String> foundFiles = new HashSet<String>();
    URI dirURI = dir.toURI();
    for (File f: files)
        foundFiles.add(dirURI.relativize(f.toURI()).getPath());
    checkFiles(foundFiles, expectFiles, dir);
}
 
Example 7
Project: CustomWorldGen   File: ZipperUtil.java   View Source Code Vote up 5 votes
public static void zip(File directory, File zipfile) throws IOException
{
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<File>();
    queue.push(directory);
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = null;
    try
    {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty())
        {
            directory = queue.pop();
            for (File kid : directory.listFiles())
            {
                String name = base.relativize(kid.toURI()).getPath();
                if (kid.isDirectory())
                {
                    queue.push(kid);
                    name = name.endsWith("/") ? name : name + "/";
                    zout.putNextEntry(new ZipEntry(name));
                } else
                {
                    zout.putNextEntry(new ZipEntry(name));
                    Files.copy(kid, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally
    {
        res.close();
    }
}
 
Example 8
Project: openjdk-jdk10   File: PrintCrashTest.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    printerJob.setPrintable((graphics, pageFormat, pageIndex) -> {
        if (pageIndex != 0) {
            return Printable.NO_SUCH_PAGE;
        } else {
            Shape shape = new Rectangle(110, 110, 10, 10);
            Rectangle rect = shape.getBounds();

            BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                    .getDefaultConfiguration().createCompatibleImage(rect.width, rect.height, Transparency.BITMASK);
            graphics.drawImage(image, rect.x, rect.y, rect.width, rect.height, null);

            return Printable.PAGE_EXISTS;
        }
    });

    File file = null;
    try {
        HashPrintRequestAttributeSet hashPrintRequestAttributeSet = new HashPrintRequestAttributeSet();
        file = File.createTempFile("out", "ps");
        file.deleteOnExit();
        Destination destination = new Destination(file.toURI());
        hashPrintRequestAttributeSet.add(destination);
        printerJob.print(hashPrintRequestAttributeSet);
    } finally {
        if (file != null) {
            file.delete();
        }
    }
}
 
Example 9
Project: jdk8u-jdk   File: GetInstance.java   View Source Code Vote up 5 votes
private int testURIParam(int testnum) throws Exception {
    // get an instance of JavaPolicy from SUN and have it read from the URL

    File file = new File(System.getProperty("test.src", "."),
                            "GetInstance.policyURL");
    URI uri = file.toURI();
    Policy p = Policy.getInstance(JAVA_POLICY, new URIParameter(uri));

    doTest(p, testnum++);
    Policy.setPolicy(p);
    doTestSM(testnum++);

    return testnum;
}
 
Example 10
Project: openjdk-jdk10   File: Options.java   View Source Code Vote up 5 votes
/**
 * Adds a new catalog file.Use created or existed resolver to parse new catalog file.
 *
 * @param catalogFile
 * @throws java.io.IOException
 */
public void addCatalog(File catalogFile) throws IOException {
    URI newUri = catalogFile.toURI();
    if (!catalogUrls.contains(newUri)) {
        catalogUrls.add(newUri);
    }
    entityResolver = CatalogUtil.getCatalog(entityResolver, catalogFile, catalogUrls);
}
 
Example 11
Project: defense-solutions-proofs-of-concept   File: AppConfigController.java   View Source Code Vote up 5 votes
/**
 * Returns the file that will be read when resetting application configuration
 * settings. This file may or may not actually exist.
 * @return the file that will be read when resetting application configuration
 *         settings.
 */
private URI getAppConfigFileUri() throws URISyntaxException {
    File configFile = new File("./appconfig.xml");
    if (configFile.exists()) {
        return configFile.toURI();
    } else {
        return getClass().getResource("/com/esri/vehiclecommander/resources/appconfig.xml").toURI();
    }
}
 
Example 12
Project: incubator-netbeans   File: AbstractSvnTestCase.java   View Source Code Vote up 5 votes
protected String getPathRelativeToWC(File file) {
    URI wcURI = getWC().toURI();
    URI fileURI = file.toURI();
    URI relativePathURI = wcURI.relativize(fileURI);
    if (relativePathURI == fileURI) {
        throw new IllegalArgumentException(
                "The given file is not in the working directory.");
    }
    return relativePathURI.getPath();
}
 
Example 13
Project: guava-mock   File: ClassPathTest.java   View Source Code Vote up 5 votes
@Override protected void scanDirectory(ClassLoader loader, File root) throws IOException {
  URI base = root.toURI();
  for (File entry : Files.fileTreeTraverser().preOrderTraversal(root)) {
    String resourceName = new File(base.relativize(entry.toURI()).getPath()).getPath();
    resources.add(resourceName);
  }
}
 
Example 14
Project: ditb   File: TestImportExport.java   View Source Code Vote up 5 votes
/**
 * Test import data from 0.94 exported file
 * @throws Exception
 */
@Test
public void testImport94Table() throws Exception {
  final String name = "exportedTableIn94Format";
  URL url = TestImportExport.class.getResource(name);
  File f = new File(url.toURI());
  if (!f.exists()) {
    LOG.warn("FAILED TO FIND " + f + "; skipping out on test");
    return;
  }
  assertTrue(f.exists());
  LOG.info("FILE=" + f);
  Path importPath = new Path(f.toURI());
  FileSystem fs = FileSystem.get(UTIL.getConfiguration());
  fs.copyFromLocalFile(importPath, new Path(FQ_OUTPUT_DIR + Path.SEPARATOR + name));
  String IMPORT_TABLE = name;
  try (Table t = UTIL.createTable(TableName.valueOf(IMPORT_TABLE), Bytes.toBytes("f1"), 3);) {
    String[] args = new String[] {
        "-Dhbase.import.version=0.94" ,
        IMPORT_TABLE, FQ_OUTPUT_DIR
    };
    assertTrue(runImport(args));
    /* exportedTableIn94Format contains 5 rows
    ROW         COLUMN+CELL
    r1          column=f1:c1, timestamp=1383766761171, value=val1
    r2          column=f1:c1, timestamp=1383766771642, value=val2
    r3          column=f1:c1, timestamp=1383766777615, value=val3
    r4          column=f1:c1, timestamp=1383766785146, value=val4
    r5          column=f1:c1, timestamp=1383766791506, value=val5
    */
   assertEquals(5, UTIL.countRows(t));
  }
}
 
Example 15
Project: openjdk-jdk10   File: APITest.java   View Source Code Vote up 5 votes
protected void checkFiles(File dir, Set<String> expectFiles) {
    Set<File> files = new HashSet<File>();
    listFiles(dir, files);
    Set<String> foundFiles = new HashSet<String>();
    URI dirURI = dir.toURI();
    for (File f: files)
        foundFiles.add(dirURI.relativize(f.toURI()).getPath());
    checkFiles(foundFiles, expectFiles, dir);
}
 
Example 16
Project: attics   File: Song.java   View Source Code Vote up 5 votes
public Song(String name, String title, int track, String album, String length, String itemIdentifier) {
    this.name = name;
    this.title = title;
    this.track = track;
    this.album = album;
    this.length = length;
    this.itemIdentifier = itemIdentifier;

    try {
        File temp = new File(String.format("items/%s/%s.mp3", itemIdentifier, title));
        filePath = temp.toURI();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}
 
Example 17
Project: Reer   File: ResourceExceptions.java   View Source Code Vote up 4 votes
public static ResourceIsAFolderException readFolder(File location) {
    return new ResourceIsAFolderException(location.toURI(), String.format("Cannot read '%s' because it is a folder.", location));
}
 
Example 18
Project: Reer   File: ExternalResourceResolverDescriptorParseContext.java   View Source Code Vote up 4 votes
public LocallyAvailableExternalResource getMetaDataArtifact(ModuleComponentIdentifier moduleComponentIdentifier, ArtifactType artifactType) {
    File resolvedArtifactFile = resolveMetaDataArtifactFile(moduleComponentIdentifier, mainResolvers.getComponentResolver(), mainResolvers.getArtifactResolver(), artifactType);
    LocallyAvailableResource localResource = new DefaultLocallyAvailableResource(resolvedArtifactFile);
    return new DefaultLocallyAvailableExternalResource(resolvedArtifactFile.toURI(), localResource);
}
 
Example 19
Project: circus-train   File: GraphiteLoaderTest.java   View Source Code Vote up 4 votes
@Before
public void before() {
  clusterProperties = new File(temp.getRoot(), "cluster.properties");
  path = new Path(clusterProperties.toURI());
  loader = new GraphiteLoader(conf);
}
 
Example 20
Project: hadoop   File: TestFileUtil.java   View Source Code Vote up 4 votes
@Test (timeout = 30000)
/*
 * Test method copy(FileSystem srcFS, Path src, File dst, boolean deleteSource, Configuration conf)
 */
public void testCopy5() throws IOException {
  setupDirs();
  
  URI uri = tmp.toURI();
  Configuration conf = new Configuration();
  FileSystem fs = FileSystem.newInstance(uri, conf);
  final String content = "some-content";
  File srcFile = createFile(tmp, "src", content);
  Path srcPath = new Path(srcFile.toURI());
  
  // copy regular file:
  final File dest = new File(del, "dest");
  boolean result = FileUtil.copy(fs, srcPath, dest, false, conf);
  assertTrue(result);
  assertTrue(dest.exists());
  assertEquals(content.getBytes().length 
      + System.getProperty("line.separator").getBytes().length, dest.length());
  assertTrue(srcFile.exists()); // should not be deleted
  
  // copy regular file, delete src:
  dest.delete();
  assertTrue(!dest.exists());
  result = FileUtil.copy(fs, srcPath, dest, true, conf);
  assertTrue(result);
  assertTrue(dest.exists());
  assertEquals(content.getBytes().length 
      + System.getProperty("line.separator").getBytes().length, dest.length());
  assertTrue(!srcFile.exists()); // should be deleted
  
  // copy a dir:
  dest.delete();
  assertTrue(!dest.exists());
  srcPath = new Path(partitioned.toURI());
  result = FileUtil.copy(fs, srcPath, dest, true, conf);
  assertTrue(result);
  assertTrue(dest.exists() && dest.isDirectory());
  File[] files = dest.listFiles();
  assertTrue(files != null);
  assertEquals(2, files.length);
  for (File f: files) {
    assertEquals(3 
        + System.getProperty("line.separator").getBytes().length, f.length());
  }
  assertTrue(!partitioned.exists()); // should be deleted
}