Example usage for org.apache.commons.io FileUtils toFile

List of usage examples for org.apache.commons.io FileUtils toFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils toFile.

Prototype

public static File toFile(URL url) 

Source Link

Document

Convert from a URL to a File.

Usage

From source file:com.ctsim.simemua_instructor.ACarControlPanelFrame.java

private void initImage() {
    try {//from  w w  w  . j  a v  a 2s.co m
        aCarControlPanelImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/layout_a-car_control_panel.png")));
        mainBreakerOnImg = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/main_breaker_on.png")));
        mainBreakerOffImg = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/main_breaker_off.png")));
        breakerOnImg = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/breaker_on.png")));
        breakerOffImg = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/breaker_off.png")));
        switchByPassOnImg = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/switch_bypass_on.png")));
        switchByPassOffImg = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/switch_bypass_off.png")));
        switchPBPermitOnImg = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/switch_pb_permit_on.png")));
        switchPBPermitOffImg = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/switch_pb_permit_off.png")));
        switchYesNoBlackOnImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_yes-no_black_on.png")));
        switchYesNoBlackOffImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_yes-no_black_off.png")));
        switchPBSquareBlackOnImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_pb_square_black_on.png")));
        switchPBSquareBlackOffImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_pb_square_black_off.png")));
        switchRotaryBlackIdleImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_rotary_black_idle.png")));
        switchRotaryYellowIdleOffImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_rotary_yellow_idle_off.png")));
        switchRotaryYellowOnImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_rotary_yellow_on.png")));
        switchRotaryYellowIdleOnImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_rotary_yellow_idle_on.png")));
        switchRotaryYellowOffImg = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/switch_rotary_yellow_off.png")));
        lampRedOnImg = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/lamp_red_on.png")));
        lampRedOffImg = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/lamp_red_off.png")));
        lampYellowOnImg = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/lamp_yellow_on.png")));
        lampYellowOffImg = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/lamp_yellow_off.png")));

    } catch (IOException ex) {
        Logger.getLogger(ACarControlPanelFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.pms.util.FilePermissionsTest.java

@Test
public void testFilePermissions() throws URISyntaxException, IOException {
    FilePermissions permissions = new FilePermissions(new File(""));
    assertTrue("CurrentFolderIsFolder", permissions.isFolder());
    assertTrue("CurrentFolderIsReadable", permissions.isReadable());
    assertTrue("CurrentFolderIsBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(Paths.get("").toAbsolutePath());
    assertTrue("CurrentFolderIsFolder", permissions.isFolder());
    assertTrue("CurrentFolderIsReadable", permissions.isReadable());
    assertTrue("CurrentFolderIsBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(FileUtils.toFile(CLASS.getResource("english-utf8-with-bom.srt")));
    assertTrue("FileIsReadable", permissions.isReadable());
    assertTrue("FileIsWritable", permissions.isWritable());
    assertFalse("FileIsNotFolder", permissions.isFolder());
    assertFalse("FileIsNotBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(permissions.getFile().getParentFile());
    assertTrue("ParentIsFolder", permissions.isFolder());
    assertTrue("ParentIsBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(Paths.get(CLASS.getResource("english-utf8-with-bom.srt").toURI()));
    assertTrue("FileIsReadable", permissions.isReadable());
    assertTrue("FileIsWritable", permissions.isWritable());
    assertFalse("FileIsNotFolder", permissions.isFolder());
    assertFalse("FileIsNotBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(permissions.getPath().getParent());
    assertTrue("ParentIsFolder", permissions.isFolder());
    assertTrue("ParentIsBrowsable", permissions.isBrowsable());

    File file = new File(System.getProperty("java.io.tmpdir"),
            String.format("UMS_temp_writable_file_%d.tmp", new Random().nextInt(10000)));
    if (file.createNewFile()) {
        try {//from ww w. j a va  2s  .co  m
            assertTrue("TempFileIsReadable", new FilePermissions(file).isReadable());
            assertTrue("TempFileIsWritable", new FilePermissions(file).isWritable());
            assertFalse("TempFileIsNotFolder", new FilePermissions(file).isFolder());
            assertFalse("TempFileIsNotBrowsable", new FilePermissions(file).isBrowsable());
        } finally {
            file.delete();
        }
    }

    Path path = Paths.get(System.getProperty("java.io.tmpdir"),
            String.format("UMS_temp_writable_file_%d.tmp", new Random().nextInt(10000)));
    Files.createFile(path);
    try {
        assertTrue("TempFileIsReadable", new FilePermissions(path).isReadable());
        assertTrue("TempFileIsWritable", new FilePermissions(path).isWritable());
        assertFalse("TempFileIsNotFolder", new FilePermissions(path).isFolder());
        assertFalse("TempFileIsNotBrowsable", new FilePermissions(path).isBrowsable());
    } finally {
        Files.delete(path);
    }
}

From source file:net.pms.util.FileUtilTest.java

@Test
public void testGetFileCharset_UTF16_BE() throws Exception {
    File file = FileUtils.toFile(CLASS.getResource("russian-utf16-be.srt"));
    assertThat(FileUtil.getFileCharset(file)).isEqualTo(Constants.CHARSET_UTF_16BE);
}

From source file:com.ctsim.dmi.MainFrame.java

/**
 * Creates new form MainFrame/*from  w ww  .j  a va  2  s. c  om*/
 */
public MainFrame() {
    initComponents();

    timer = new Timer(30, this);
    timer.start();

    t1 = Calendar.getInstance();

    try {
        brake_indicator_yellow = ImageIO.read(FileUtils
                .toFile(this.getClass().getClassLoader().getResource("img/brake_indicator_yellow.png")));
        brake_indicator_red = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/brake_indicator_red.png")));
        speedoDial = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/speedo_dial.png")));
        speedoPinWhite = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/speedo_pin_white.png")));
        speedoPinYellow = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/speedo_pin_yellow.png")));
        speedoPinRed = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/speedo_pin_red.png")));
        targetDestination = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/target_destination.png")));
        atp_status_auto = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_auto.png")));
        atp_status_mcs = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_mcs.png")));
        atp_status_atb = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_atb.png")));
        atp_status_yard_sr = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_yard_sr.png")));
        atp_status_yard_eoa = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_yard_eoa.png")));
        atp_status_line_sr = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_line_sr.png")));
        atp_status_rv = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_rv.png")));
        atp_blank = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_blank.png")));
        atenna_yellow = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atena_yellow.png")));
        atenna_green = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atena_green.png")));
        atenna_fail = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atena_fail.png")));
        ato_status_ok = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/ato_status_ok.png")));
        ato_status_fail = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/ato_status_fail.png")));
        door_indicator_both = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_indicator_both.png")));
        door_indicator_left = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_indicator_left.png")));
        door_indicator_right = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_indicator_right.png")));
        door_status_close = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_status_close.png")));
        door_status_open = ImageIO.read(
                FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_status_open.png")));
        scroll_arrow = ImageIO
                .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/scroll_arrow.png")));
    } catch (IOException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:edu.harvard.i2b2.fhirserver.ws.FileServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get requested file by path info.

    String requestedFile = request.getPathInfo();

    if (requestedFile.equals("/"))
        requestedFile = "/index.html";
    logger.trace("Got request:" + requestedFile);
    logger.trace("basePath:" + this.basePath);
    logger.trace("ffp:" + basePath + requestedFile);

    // Check if file is actually supplied to the request URI.
    //if (requestedFile == null) {
    // Do your thing if the file is not supplied to the request URI.
    // Throw an exception, or send 404, or show default/warning page, or just ignore it.
    //  response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
    //return;//from  www.  j a  v  a2 s.  c om
    //}

    // Decode the file name (might contain spaces and on) and prepare file object.
    URL url = new URL(basePath + requestedFile);
    logger.trace("url:" + url);
    File file = FileUtils.toFile(url);
    logger.trace("searching for file:" + file.getAbsolutePath());

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName());

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/text";
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    //  response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:com.itemanalysis.psychometrics.polycor.CovarianceMatrixTest.java

public double[][] getCovariance() {
    double[][] x = new double[50][50];
    try {/*www .ja va  2 s  .  c o m*/
        File f = FileUtils.toFile(this.getClass().getResource("/testdata/covariance-scaling-data.txt"));
        BufferedReader br = new BufferedReader(new FileReader(f));
        String line = "";
        String[] s = null;
        int row = 0;
        br.readLine();//eliminate column names by skipping first row
        while ((line = br.readLine()) != null) {
            s = line.split(",");
            for (int j = 0; j < 50; j++) {
                x[row][j] = Double.parseDouble(s[j]);
            }
            row++;
        }
        br.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return x;
}

From source file:com.skype.SkypeAPIConnector.java

@Start
public void createSkypeConnector() {
    this.skype = new Skype();
    this.pemFile = FileUtils.toFile(this.getClass().getClassLoader().getResource(pemFileName));
    this.listener = new MuleSkypeWrapper();
}

From source file:com.garethahealy.camel.file.loadbalancer.example1.routes.Read99FilesWithThreeReadersTest.java

@Test
public void readThreeFilesWithThreeReaders() throws InterruptedException, MalformedURLException {
    Map<String, String> answer = getRouteToEndpointPriority();

    //Used for debugging purposes, in-case we need to know which endpoint has what priority
    LOG.info("EndpointSetup: " + answer.toString());

    MockEndpoint first = getMockEndpoint("mock:endFirst");
    first.setExpectedMessageCount(33);// www.  j  a  v a2 s . c o m
    first.setResultWaitTime(TimeUnit.SECONDS.toMillis(15));
    first.setAssertPeriod(TimeUnit.SECONDS.toMillis(1));

    MockEndpoint second = getMockEndpoint("mock:endSecond");
    second.setExpectedMessageCount(33);
    second.setResultWaitTime(TimeUnit.SECONDS.toMillis(15));
    second.setAssertPeriod(TimeUnit.SECONDS.toMillis(1));

    MockEndpoint third = getMockEndpoint("mock:endThird");
    third.setExpectedMessageCount(33);
    third.setResultWaitTime(TimeUnit.SECONDS.toMillis(15));
    third.setAssertPeriod(TimeUnit.SECONDS.toMillis(1));

    //Wait for the files to be processed
    sleep(30);

    File firstDirectory = FileUtils.toFile(new URL("file:" + rootDirectory + "/.camel0"));
    File secondDirectory = FileUtils.toFile(new URL("file:" + rootDirectory + "/.camel1"));
    File thirdDirectory = FileUtils.toFile(new URL("file:" + rootDirectory + "/.camel2"));

    Assert.assertTrue(".camel0 doesnt exist", firstDirectory.exists());
    Assert.assertTrue(".camel1 doesnt exist", secondDirectory.exists());
    Assert.assertTrue(".camel2 doesnt exist", thirdDirectory.exists());

    Collection<File> firstFiles = FileUtils.listFiles(firstDirectory, FileFilterUtils.fileFileFilter(), null);
    Collection<File> secondFiles = FileUtils.listFiles(secondDirectory, FileFilterUtils.fileFileFilter(), null);
    Collection<File> thirdFiles = FileUtils.listFiles(thirdDirectory, FileFilterUtils.fileFileFilter(), null);

    Assert.assertNotNull(firstFiles);
    Assert.assertNotNull(secondFiles);
    Assert.assertNotNull(thirdFiles);

    //Check the files are unique, and we haven't copied the same file twice
    int firstSize = firstFiles.size();
    int secondSize = secondFiles.size();
    int thirdSize = thirdFiles.size();

    firstFiles.removeAll(secondFiles);
    firstFiles.removeAll(thirdFiles);

    secondFiles.removeAll(firstFiles);
    secondFiles.removeAll(thirdFiles);

    thirdFiles.removeAll(firstFiles);
    thirdFiles.removeAll(secondFiles);

    //If these numbers don't match, we duplicated a file
    Assert.assertEquals("duplicate copy in .camel0", new Integer(firstSize), new Integer(firstFiles.size()));
    Assert.assertEquals("duplicate copy in .camel1", new Integer(secondSize), new Integer(secondFiles.size()));
    Assert.assertEquals("duplicate copy in .camel2", new Integer(thirdSize), new Integer(thirdFiles.size()));

    //Check the expected copied amount is correct
    Assert.assertEquals(new Integer(33), new Integer(firstFiles.size()));
    Assert.assertEquals(new Integer(33), new Integer(secondFiles.size()));
    Assert.assertEquals(new Integer(33), new Integer(thirdFiles.size()));
    Assert.assertEquals(new Integer(99),
            new Integer(firstFiles.size() + secondFiles.size() + thirdFiles.size()));

    //Assert the endpoints last, as there seems to be a strange bug where they fail but the files have been processed,
    //so that would suggest the MockEndpoints are reporting a false-positive
    first.assertIsSatisfied();
    second.assertIsSatisfied();
    third.assertIsSatisfied();
}

From source file:com.navercorp.pinpoint.bootstrap.AgentDirBaseClassPathResolverTest.java

private static String getClassLocation(Class<?> clazz) {
    CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
    URL location = codeSource.getLocation();
    logger.debug("codeSource.getLocation:{}", location);
    File file = FileUtils.toFile(location);
    return file.getPath();
}

From source file:com.navercorp.pinpoint.bootstrap.agentdir.AgentDirBaseClassPathResolverTest.java

private static String getClassLocation(Class<?> clazz) {
    URL location = CodeSourceUtils.getCodeLocation(clazz);
    logger.debug("codeSource.getCodeLocation:{}", location);
    File file = FileUtils.toFile(location);
    return file.getPath();
}