Java Code Examples for java.io.File#toString()

The following examples show how to use java.io.File#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TaskManagerRunnerConfigurationTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadDynamicalProperties() throws IOException, FlinkParseException {
	final File tmpDir = temporaryFolder.newFolder();
	final File confFile = new File(tmpDir, GlobalConfiguration.FLINK_CONF_FILENAME);
	final PrintWriter pw1 = new PrintWriter(confFile);
	final long managedMemory = 1024 * 1024 * 256;
	pw1.println(JobManagerOptions.ADDRESS.key() + ": localhost");
	pw1.println(TaskManagerOptions.MANAGED_MEMORY_SIZE.key() + ": " + managedMemory + "b");
	pw1.close();

	final String jmHost = "host1";
	final int jmPort = 12345;
	String[] args = new String[] {
		"--configDir", tmpDir.toString(),
		"-D" + JobManagerOptions.ADDRESS.key() + "=" + jmHost,
		"-D" + JobManagerOptions.PORT.key() + "=" + jmPort
	};
	Configuration configuration = TaskManagerRunner.loadConfiguration(args);
	assertEquals(MemorySize.parse(managedMemory + "b"), configuration.get(TaskManagerOptions.MANAGED_MEMORY_SIZE));
	assertEquals(jmHost, configuration.get(JobManagerOptions.ADDRESS));
	assertEquals(jmPort, configuration.getInteger(JobManagerOptions.PORT));
}
 
Example 2
Source File: CountFalsePositivesIntegrationTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSimple() throws Exception {
    final File dreamDir =  new File(publicTestDir, "org/broadinstitute/hellbender/tools/mutect/dream");
    final File output = createTempFile("output", ".txt");
    final String[] args = {
            "-V", dreamDir + "/vcfs/dream3-chr20.vcf",
            "-R", b37_reference_20_21,
            "-L", dreamDir + "/dream-chr20.interval_list",
            "-O", output.toString()
    };
    runCommandLine(args);

    FalsePositiveRecordReader reader = new FalsePositiveRecordReader(output);
    FalsePositiveRecord record = reader.readRecord();

    // check that the tool agrees with the false positive counts using AWK
    // SNP: grep PASS dream3-chr20.vcf | awk 'length($4) == length($5) { print $0 }' | wc -l
    // INDEL: grep PASS dream3-chr20.vcf | awk 'length($4) != length($5) { print $0 }' | wc -l
    Assert.assertEquals(record.getSnpFalsePositives(), 173);
    Assert.assertEquals(record.getIndelFalsePositives(), 276);
}
 
Example 3
Source File: JasperRunManager.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Fills a report and saves it directly into a PDF file. 
 * The intermediate JasperPrint object is not saved on disk.
 */
public String runToPdfFile(
	String sourceFileName, 
	Map<String,Object> params, 
	JRDataSource jrDataSource
	) throws JRException
{
	File sourceFile = new File(sourceFileName);

	/*   */
	JasperPrint jasperPrint = JRFiller.fill(jasperReportsContext, 
			JasperFillManager.getReportSource(jasperReportsContext, sourceFile), 
			params, jrDataSource);

	/*   */
	File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".pdf");
	String destFileName = destFile.toString();

	JasperExportManager.getInstance(jasperReportsContext).exportToPdfFile(jasperPrint, destFileName);
	
	return destFileName;
}
 
Example 4
Source File: Save.java    From minicraft-plus-revived with GNU General Public License v3.0 6 votes vote down vote up
private Save(File worldFolder) {
	data = new ArrayList<>();
	
	
	if(worldFolder.getParent().equals("saves")) {
		String worldName = worldFolder.getName();
		if (!worldName.toLowerCase().equals(worldName)) {
			if (Game.debug) System.out.println("Renaming world in " + worldFolder + " to lowercase");
			String path = worldFolder.toString();
			path = path.substring(0, path.lastIndexOf(worldName));
			File newFolder = new File(path + worldName.toLowerCase());
			if (worldFolder.renameTo(newFolder))
				worldFolder = newFolder;
			else
				System.err.println("Failed to rename world folder " + worldFolder + " to " + newFolder);
		}
	}
	
	folder = worldFolder;
	location = worldFolder.getPath() + "/";
	
	folder.mkdirs();
}
 
Example 5
Source File: ClassLoaderHelper.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an alternate path name for the given file
 * such that if the original pathname did not exist, then the
 * file may be located at the alternate location.
 * For mac, this replaces the final .dylib suffix with .jnilib
 */
static File mapAlternativeName(File lib) {
    String name = lib.toString();
    int index = name.lastIndexOf('.');
    if (index < 0) {
        return null;
    }
    return new File(name.substring(0, index) + ".jnilib");
}
 
Example 6
Source File: StringUtil.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取工程路径
 *
 * @return
 */
public static String getProjectPath(String fileName, String relativeUiPath) {
	String projectPath = "";
	try {
		File file = new DefaultResourceLoader().getResource("").getFile();
		if (file != null) {
			while (true) {
				File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
				if (f == null || f.exists()) {
					break;
				}
				if (file.getParentFile() != null) {
					file = file.getParentFile();
				} else {
					break;
				}
			}
			if (!fileName.endsWith(DOT_JAVA) && isNotEmpty(relativeUiPath)) {
				File fileTemp = new File(file.getPath() + File.separator + relativeUiPath);
				if (fileTemp == null || fileTemp.exists()) {
					file = fileTemp;
				}
			}

			projectPath = file.toString();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	return projectPath;
}
 
Example 7
Source File: TakePhotoFragment.java    From PictureSelector with Apache License 2.0 5 votes vote down vote up
private void choosePhotoFromCamera() {
    String dir = getTakePhotoDir();
    File photoDir = new File(dir);
    if (!photoDir.exists()) {
        //noinspection ResultOfMethodCallIgnored
        photoDir.mkdirs();
    }
    File mCurrentFile = new File(dir, getPhotoName());
    mImagePath = mCurrentFile.toString();
    Intent intent = getCameraIntent(mCurrentFile);
    startActivityForResult(intent, ConstantData.REQUEST_CODE_TAKE_PHOTO);
    getActivity().overridePendingTransition(0, 0);
}
 
Example 8
Source File: TestUtilHid.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public final static  void destroyLocalFileSystem (String testName) throws IOException {            
    File mountPoint = TestUtilHid.locationOfTempFolder("lfstest");
    
    if (mountPoint.exists()) {
            if (TestUtilHid.deleteFolder(mountPoint) == false)
                throw new IOException("Cannot delete test folder: " + mountPoint.toString());
    }
    
}
 
Example 9
Source File: AccumuloUtil.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 5 votes vote down vote up
/**
 * Add the .jar elements of a directory to the DCache classpath, optionally
 * recursively.
 */
private static void addDirToCache(File dir, FileSystem fs,
  Set<String> localUrls, boolean recursive) {
  if (dir != null) {
    File[] fileList = dir.listFiles();

    if (fileList != null) {
      for (File libFile : dir.listFiles()) {
        if (libFile.exists() && !libFile.isDirectory()
          && libFile.getName().endsWith("jar")) {
          Path p = new Path(libFile.toString());
          if (libFile.canRead()) {
            String qualified = p.makeQualified(fs).toString();
            LOG.info("Adding to job classpath: " + qualified);
            localUrls.add(qualified);
          } else {
            LOG.warn("Ignoring unreadable file " + libFile);
          }
        }
        if (recursive && libFile.isDirectory()) {
          addDirToCache(libFile, fs, localUrls, recursive);
        }
      }
    } else {
      LOG.warn("No files under " + dir
        + " to add to distributed cache for Accumulo job");
    }
  }
}
 
Example 10
Source File: PackageStuff.java    From open-ig with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Add the given fileName to the zip stream with the given entry name.
 * @param entryName the entry name
 * @param fileName the file name and path
 * @param zout the output stream
 * @throws IOException on error
 */
static void addFile(String entryName, String fileName, ZipOutputStream zout)
throws IOException {
	ZipEntry mf = new ZipEntry(entryName);
	File mfm = new File(fileName);
	if (mfm.canRead()) {
		mf.setSize(mfm.length());
		mf.setTime(mfm.lastModified());
		zout.putNextEntry(mf);
		zout.write(IOUtils.load(mfm));
	} else {
		throw new RuntimeException("File not found: " + mfm.toString());
	}
}
 
Example 11
Source File: NugetInspectorManager.java    From hub-detect with Apache License 2.0 5 votes vote down vote up
private DotNetCoreNugetInspector findDotnetCoreInspector(File nupkgFolder, String dotnetExecutable) throws DetectorException {
    //new inspector
    final String dotnetInspectorName = "BlackduckNugetInspector.dll";
    logger.info("Searching for: " + dotnetInspectorName);
    File toolsFolder = new File(nupkgFolder, "tools");
    Optional<File> foundExe = detectFileFinder.findFilesToDepth(toolsFolder, dotnetInspectorName, 3).stream().findFirst();
    if (foundExe.isPresent() && foundExe.get().exists()) {
        String inspectorExe = foundExe.get().toString();
        logger.info("Found nuget inspector: " + inspectorExe);
        return new DotNetCoreNugetInspector(dotnetExecutable, inspectorExe, executableRunner);
    } else {
        throw new DetectorException("Unable to find nuget inspector, looking for " + dotnetInspectorName + " in " + toolsFolder.toString());
    }
}
 
Example 12
Source File: AdbRunner.java    From AndroidDesignPreview with Apache License 2.0 5 votes vote down vote up
private File extractAssetToCacheDirectory(String assetPath, String filename, boolean force)
        throws ProoferException {
    File outFile = new File(Util.getCacheDirectory(), filename);
    if (force || !outFile.exists()) {
        if (!Util.extractResource("assets/" + assetPath, outFile)) {
            throw new ProoferException("Error extracting to " + outFile.toString());
        }
    }
    return outFile;
}
 
Example 13
Source File: JasperExportManager.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Exports the generated report file specified by the parameter into PDF format.
 * The resulting PDF file has the same name as the report object inside the source file,
 * plus the <code>*.pdf</code> extension and it is located in the same directory as the source file.
 *  
 * @param sourceFileName source file containing the generated report
 * @return resulting PDF file name
 * @see net.sf.jasperreports.engine.export.JRPdfExporter
 */
public String exportToPdfFile(String sourceFileName) throws JRException
{
	File sourceFile = new File(sourceFileName);

	/* We need the report name. */
	JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);

	File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".pdf");
	String destFileName = destFile.toString();
	
	exportToPdfFile(jasperPrint, destFileName);
	
	return destFileName;
}
 
Example 14
Source File: FileUtils.java    From Notebook with Apache License 2.0 5 votes vote down vote up
public static boolean deleteDirectory(String path,String fileName) {
	boolean status;
	SecurityManager checker = new SecurityManager();

	if (!fileName.equals("")) {

		File newPath = new File(path.toString() + fileName);
		checker.checkDelete(newPath.toString());
		if (newPath.isDirectory()) {
			String[] listfile = newPath.list();
			try {
				for (int i = 0; i < listfile.length; i++) {
					File deletedFile = new File(newPath.toString() + "/"
							+ listfile[i].toString());
					deletedFile.delete();
				}
				newPath.delete();
				System.out.println("DirectoryManager deleteDirectory"+ fileName);
				status = true;
			} catch (Exception e) {
				e.printStackTrace();
				status = false;
			}

		} else
			status = false;
	} else
		status = false;
	return status;
}
 
Example 15
Source File: Driver.java    From access2csv with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	final OptionParser parser = new OptionParser();

	final OptionSpec<Void> help = parser.acceptsAll(Arrays.asList("help")).forHelp();
	final OptionSpec<String> schema = parser.accepts("schema").withOptionalArg()
			.describedAs("The schema is written to standard output.");
	final OptionSpec<String> withHeader = parser.accepts("with-header").withOptionalArg()
			.describedAs("When with-header is included, a header line of column names is written to each data file.");
	final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required()
			.describedAs("The input accdb file.");
	final OptionSpec<String> table = parser.accepts("table").withRequiredArg().ofType(String.class).describedAs("The table name to export, or all if it is not specified.");
	final OptionSpec<File> output = parser.accepts("output").requiredUnless("schema").withRequiredArg().ofType(File.class)
			.describedAs("The output directory for data files. This is required for writing data output. This not required for schema output.");
	final OptionSpec<String> csvPrefix = parser.accepts("csv-prefix").withRequiredArg().ofType(String.class).defaultsTo("").describedAs("A prefix to add to all of the generated CSV file names");    
	final OptionSpec<Boolean> quoteAll = parser.accepts("quote-all").withOptionalArg().ofType(Boolean.class).defaultsTo(true)
			.describedAs("Set quote-all to true if all values are to be quoted. " +
			"Set to false if quotes are only to be applied to values which contain " + 
			"the separator, secape, quote, or new line characters. The default is true.");
	final OptionSpec<String> writeNull = parser.accepts("write-null").withOptionalArg().ofType(String.class).defaultsTo("")
			.describedAs("The text to write when entry is NULL. Defaults to empty output if not specified or if no argument supplied. " +
			"If quote-all is set to true then the value for write-null is also quoted.");
  
   
	OptionSet options = null;

	try {
		options = parser.parse(args);
	} catch (final OptionException e) {
		System.out.println(e.getMessage());
		parser.printHelpOn(System.out);
		throw e;
	}

	if (options.has(help)) {
		parser.printHelpOn(System.out);
		return;
	}
     
	File inputFile = input.value(options);
	if(!inputFile.exists()) {
		throw new FileNotFoundException("Could not find input file: " + inputFile.toString());
	}
	
	File outputDir = null;
	if (options.has(output)) {
		outputDir = output.value(options);
		if(!outputDir.exists()) {
			outputDir.mkdirs();
		}	
	}
   		
	boolean applyQuotesToAll = quoteAll.value(options);    
   String nullText = writeNull.value(options);
   
	if (options.has(schema)) {
		schema(inputFile);
	}
	
	if (null != outputDir) {
		if (options.has(table)){
			export(inputFile, table.value(options), options.has(withHeader), outputDir, csvPrefix.value(options), applyQuotesToAll, nullText);
		}
		else {
			exportAll(inputFile, options.has(withHeader), outputDir, csvPrefix.value(options), applyQuotesToAll, nullText);
		}	
	}
}
 
Example 16
Source File: BdsNode.java    From BigDataScript with Apache License 2.0 4 votes vote down vote up
public String getFileName() {
	File f = getFile();
	return f == null ? null : f.toString();
}
 
Example 17
Source File: EglSurfaceBase.java    From FuAgoraDemoDroid with MIT License 4 votes vote down vote up
/**
 * Saves the EGL surface to a file.
 * <p>
 * Expects that this object's EGL surface is current.
 */
public void saveFrame(File file) throws IOException {
    if (!mEglCore.isCurrent(mEGLSurface)) {
        throw new RuntimeException("Expected EGL context/surface is not current");
    }

    // glReadPixels fills in a "direct" ByteBuffer with what is essentially big-endian RGBA
    // data (i.e. a byte of red, followed by a byte of green...).  While the Bitmap
    // constructor that takes an int[] wants little-endian ARGB (blue/red swapped), the
    // Bitmap "copy pixels" method wants the same format GL provides.
    //
    // Ideally we'd have some way to re-use the ByteBuffer, especially if we're calling
    // here often.
    //
    // Making this even more interesting is the upside-down nature of GL, which means
    // our output will look upside down relative to what appears on screen if the
    // typical GL conventions are used.

    String filename = file.toString();

    int width = getWidth();
    int height = getHeight();
    ByteBuffer buf = ByteBuffer.allocateDirect(width * height * 4);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    GLES20.glReadPixels(0, 0, width, height,
            GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf);
    GlUtil.checkGlError("glReadPixels");
    buf.rewind();

    BufferedOutputStream bos = null;
    try {
        bos = new BufferedOutputStream(new FileOutputStream(filename));
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bmp.copyPixelsFromBuffer(buf);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, bos);
        bmp.recycle();
    } finally {
        if (bos != null)
            bos.close();
    }
    Log.d(TAG, "Saved " + width + "x" + height + " frame as '" + filename + "'");
}
 
Example 18
Source File: Config.java    From Nukkit with GNU General Public License v3.0 4 votes vote down vote up
@Deprecated
public Config(File file, int type, LinkedHashMap<String, Object> defaultMap) {
    this(file.toString(), type, new ConfigSection(defaultMap));
}
 
Example 19
Source File: TemplateParameterEditorDialog.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
private void addComponents() {
    Property property = getProperty();
    try {
        Template template = this.modifiedParameter.getTemplate();
        property.setValue(template.getPath());
    } catch (ValidationException e) {
        logger.warning(e.getMessage());
    }

    FileEditor fileEditor = new FileEditor();
    JComponent filePathComponent = fileEditor.createEditorComponent(property.getDescriptor(), this.paramContext);
    filePathComponent.setPreferredSize(new Dimension(770, 25));

    JPanel topPanel = new JPanel(new BorderLayout());
    JPanel filePanel = new JPanel();
    final JLabel label = new JLabel("File:");
    filePanel.add(label);
    filePanel.add(filePathComponent);
    topPanel.add(filePanel, BorderLayout.NORTH);

    JPanel outFilePanel = new JPanel();
    final JLabel jLabel = new JLabel("Output File:");
    outFilePanel.add(jLabel);
    File outputFile = this.modifiedParameter.getOutputFile();
    outFileName = new JTextField(outputFile != null ? outputFile.toString() : "");
    outFileName.setPreferredSize(
            new Dimension(filePathComponent.getPreferredSize().width + label.getPreferredSize().width - jLabel.getPreferredSize().width, 25));
    org.esa.snap.utils.UIUtils.addPromptSupport(outFileName, "Enter the name of transformed file here");
    outFilePanel.add(outFileName);
    topPanel.add(outFilePanel, BorderLayout.WEST);

    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.setPreferredSize(new Dimension(800, 550));
    mainPanel.add(topPanel, BorderLayout.PAGE_START);

    //to create UI component for outputFile
    fileContentArea.setAutoCompleteEntries(getAutocompleteEntries());
    fileContentArea.setTriggerChar('$');
    mainPanel.add(new JScrollPane(fileContentArea), BorderLayout.CENTER);

    updateFileAreaContent();

    mainPanel.add(createParametersPanel(), BorderLayout.PAGE_END);

    setContent(mainPanel);
}
 
Example 20
Source File: BayesianHetPulldownCalculator.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * For a given normal or tumor BAM file, walks through the list of common SNPs,
 * {@link BayesianHetPulldownCalculator#snpIntervals}), detects heterozygous sites, and returns
 * a {@link Pulldown} containing detailed information on the called heterozygous SNP sites.
 *
 * The {@code hetCallingStrigency} parameters sets the threshold posterior for calling a Het SNP site:
 *
 *      hetPosteriorThreshold = 1 - 10^{-hetCallingStringency}
 *      hetThresholdLogOdds = log(hetPosteriorThreshold/(1-hetPosteriorThreshold))
 *                          = log(10^{hetCallingStringency} - 1)
 *
 * (see CNV-methods.pdf for details)
 *
 * @param bamFile sorted BAM file for sample
 * @param hetCallingStringency strigency for calling a Het site
 * @return Pulldown of heterozygous SNP sites in 1-based format
 */
public Pulldown getHetPulldown(final File bamFile, final double hetCallingStringency) {
    /* log odds from stringency */
    final double hetThresholdLogOdds = FastMath.log(FastMath.pow(10, hetCallingStringency) - 1);

    try (final SamReader bamReader = SamReaderFactory.makeDefault().validationStringency(validationStringency)
            .referenceSequence(refFile).open(bamFile);
         final ReferenceSequenceFileWalker refWalker = new ReferenceSequenceFileWalker(refFile)) {
        if (bamReader.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
            throw new UserException.BadInput("BAM file " + bamFile.toString() + " must be coordinate sorted.");
        }

        final Pulldown hetPulldown = new Pulldown(bamReader.getFileHeader());
        final SamLocusIterator locusIterator = getSamLocusIteratorWithDefaultFilters(bamReader);

        final int totalNumberOfSNPs = snpIntervals.size();
        logger.info("Examining " + totalNumberOfSNPs + " sites in total...");
        int locusCount = 0;
        for (final SamLocusIterator.LocusInfo locus : locusIterator) {
            if (locusCount % NUMBER_OF_SITES_PER_LOGGED_STATUS_UPDATE == 0) {
                logger.info("Examined " + locusCount + " covered sites.");
            }
            locusCount++;

            final int totalReadCount = locus.getRecordAndOffsets().size();
            if (totalReadCount <= readDepthThreshold) {
                continue;
            }
            final Nucleotide refBase = Nucleotide.valueOf(refWalker.get(locus.getSequenceIndex())
                    .getBases()[locus.getPosition() - 1]);
            if (!isProperBase(refBase)) {
                logger.warn(String.format("The reference position at %d has an unknown base call (value: %s). Even though" +
                        " this position is indicated to be a possible heterozygous SNP in the provided SNP interval list," +
                        " no inference can be made. Continuing ...", locus.getPosition(), refBase.toString()));
                continue;
            }

            final Map<Nucleotide, List<BaseQuality>> baseQualities = getPileupBaseQualities(locus);
            final Nucleotide altBase = inferAltFromPileup(baseQualities, refBase);

            /* calculate Het log odds */
            final double hetLogLikelihood = getHetLogLikelihood(baseQualities, refBase, altBase);
            final double homLogLikelihood = getHomLogLikelihood(baseQualities, refBase, altBase,
                    DEFAULT_PRIOR_REF_HOM);
            final double hetLogOdds = (hetLogLikelihood + FastMath.log(DEFAULT_PRIOR_HET)) -
                    (homLogLikelihood + FastMath.log(1 - DEFAULT_PRIOR_HET));

            if (hetLogOdds > hetThresholdLogOdds) {
                hetPulldown.add(new AllelicCount(
                        new SimpleInterval(locus.getSequenceName(), locus.getPosition(), locus.getPosition()),
                        baseQualities.get(refBase).size(), baseQualities.get(altBase).size(),
                        refBase, altBase, totalReadCount, hetLogOdds));
            }
        }

        logger.info(locusCount + " covered sites out of " + totalNumberOfSNPs + " total sites were examined.");

        return hetPulldown;

    } catch (final IOException | SAMFormatException e) {
        throw new UserException(e.getMessage());
    }
}