List of usage examples for java.io File getParent
public String getParent()
null
if this pathname does not name a parent directory. From source file:daoimplement.studentDao.java
@Override public void write_to_file(String filename) { //Create a file File file = new File(filename); if (!file.exists()) { File citydir = new File(file.getParent()); if (!citydir.exists()) citydir.mkdirs();//from w w w .j a v a 2s. c o m try { file.createNewFile(); } catch (IOException ex) { Logger.getLogger(studentDao.class.getName()).log(Level.SEVERE, null, ex); } } //write to file PrintWriter fout = null; try { fout = new PrintWriter(new BufferedWriter(new FileWriter(file))); //Get information from Database List<Student> students = template.loadAll(Student.class); for (Student st : students) { int id = st.getStudent_id(); String firstname = st.getFirst_name(); String lastname = st.getLast_name(); String gender = st.getGender(); String startdate = st.getStart_date(); String email = st.getEmail(); fout.println(id + "," + firstname + "," + lastname + "," + gender + "," + startdate + "," + email); } fout.close(); } catch (IOException ex) { Logger.getLogger(studentDao.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:net.firejack.platform.service.deployment.broker.DeployBroker.java
@Override protected ServiceResponse perform(ServiceRequest<NamedValues> request) throws Exception { Long packageId = (Long) request.getData().get("packageId"); String name = (String) request.getData().get("name"); String file = (String) request.getData().get("file"); String host = InetAddress.getLocalHost().getHostName(); if (debug) {//from ww w . ja va2s.c o m webapps = new File(System.getenv("CATALINA_HOME"), "webapps"); } InputStream stream = OPFEngine.RegistryService.getPackageArchive(packageId, file); File app = new File(webapps, name + ".temp"); FileOutputStream outputStream = FileUtils.openOutputStream(app); if (stream != null) { IOUtils.copy(stream, outputStream); IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(stream); File war = new File(app.getParent(), name); FileUtils.deleteQuietly(war); FileUtils.moveFile(app, war); } return new ServiceResponse("Deploy to server " + host + " successfully", true); }
From source file:ch.cyberduck.cli.GlobTransferItemFinderTest.java
@Test public void testFind() throws Exception { File.createTempFile("temp", ".duck"); final File f = File.createTempFile("temp", ".duck"); File.createTempFile("temp", ".false"); final CommandLineParser parser = new PosixParser(); final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[] { "--upload", "rackspace://cdn.cyberduck.ch/remote", f.getParent() + "/*.duck" }); final Set<TransferItem> found = new GlobTransferItemFinder().find(input, TerminalAction.upload, new Path("/cdn.cyberduck.ch/remote", EnumSet.of(Path.Type.file))); assertFalse(found.isEmpty());// w w w . j av a 2s . c o m assertTrue(found.contains( new TransferItem(new Path(new Path("/cdn.cyberduck.ch/remote", EnumSet.of(Path.Type.directory)), f.getName(), EnumSet.of(Path.Type.file)), new Local(f.getAbsolutePath())))); }
From source file:RolloverFileOutputStream.java
private synchronized void setFile() throws IOException { // Check directory File file = new File(_filename); _filename = file.getCanonicalPath(); file = new File(_filename); File dir = new File(file.getParent()); if (!dir.isDirectory() || !dir.canWrite()) throw new IOException("Cannot write log directory " + dir); Date now = new Date(); // Is this a rollover file? String filename = file.getName(); int i = filename.toLowerCase().indexOf(YYYY_MM_DD); if (i >= 0) { file = new File(dir, filename.substring(0, i) + _fileDateFormat.format(now) + filename.substring(i + YYYY_MM_DD.length())); }/*from w w w .j a v a 2s . c om*/ if (file.exists() && !file.canWrite()) throw new IOException("Cannot write log file " + file); // Do we need to change the output stream? if (out == null || !file.equals(_file)) { // Yep _file = file; if (!_append && file.exists()) file.renameTo(new File(file.toString() + "." + _fileBackupFormat.format(now))); OutputStream oldOut = out; out = new FileOutputStream(file.toString(), _append); if (oldOut != null) oldOut.close(); // if(log.isDebugEnabled())log.debug("Opened "+_file); } }
From source file:com.chingo247.structureapi.plan.document.PlanDocumentGenerator.java
public void generate(File targetFolder) { // Scan the folder called 'SchematicToPlan' for schematic files Iterator<File> it = FileUtils.iterateFiles(targetFolder, new String[] { "schematic" }, true); System.out.println("Files: " + targetFolder.listFiles().length); int count = 0; long start = System.currentTimeMillis(); // Generate Plans while (it.hasNext()) { File schematic = it.next(); Document d = DocumentHelper.createDocument(); d.addElement(Elements.ROOT).addElement(Elements.SETTLERCRAFT).addElement(Elements.SCHEMATIC) .setText(schematic.getName()); File plan = new File(schematic.getParent(), FilenameUtils.getBaseName(schematic.getName()) + ".xml"); try {/*from ww w . java2 s . co m*/ XMLWriter writer = new XMLWriter(new FileWriter(plan)); writer.write(d); writer.close(); StructurePlan sp = new StructurePlan(); PlanDocument pd = new PlanDocument(structureAPI.getPlanDocumentManager(), plan); pd.putPluginElement("SettlerCraft", new PlanDocumentPluginElement("SettlerCraft", pd, (Element) d.selectSingleNode("StructurePlan/SettlerCraft"))); sp.load(pd); if (sp.getCategory().equals("Default") && !schematic.getParentFile().getName().equals(targetFolder.getName())) { sp.setCategory(schematic.getParentFile().getName()); } sp.save(); } catch (DocumentException ex) { Logger.getLogger(StructurePlanManager.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | StructureDataException ex) { Logger.getLogger(StructurePlanManager.class.getName()).log(Level.SEVERE, null, ex); } count++; } if (count > 0) { StructureAPI.print("Generated " + count + " plans in " + (System.currentTimeMillis() - start) + "ms"); } }
From source file:com.redhat.red.offliner.ftest.MavenMetadataGenerateFTest.java
/** * In general, we should only have one test method per functional test. This allows for the best parallelism when we * execute the tests, especially if the setup takes some time. * * @throws Exception In case anything (anything at all) goes wrong! *///from w w w . ja va 2 s. c o m @Test public void run() throws Exception { // We only need one repo server. TestRepositoryServer server = newRepositoryServer(); // Generate some test content byte[] content = contentGenerator.newBinaryContent(1024); Dependency dep = contentGenerator.newDependency(); Model pom = contentGenerator.newPom(); pom.addDependency(dep); String path = contentGenerator.pathOf(dep); // Register the generated content by writing it to the path within the repo server's dir structure. // This way when the path is requested it can be downloaded instead of returning a 404. server.registerContent(path, content); server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content)); server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content)); // All deps imply an accompanying POM file when using the POM artifact list reader, so we have to register one of these too. Model pomDep = contentGenerator.newPomFor(dep); String pomPath = contentGenerator.pathOf(pomDep); String md5Path = pomPath + Main.MD5_SUFFIX; String shaPath = pomPath + Main.SHA_SUFFIX; String pomStr = contentGenerator.pomToString(pomDep); server.registerContent(pomPath, pomStr); server.registerContent(md5Path, md5Hex(pomStr)); server.registerContent(shaPath, sha1Hex(pomStr)); // Write the plaintext file we'll use as input. File pomFile = temporaryFolder.newFile(getClass().getSimpleName() + ".pom"); FileUtils.write(pomFile, contentGenerator.pomToString(pom)); Options opts = new Options(); opts.setBaseUrls(Collections.singletonList(server.getBaseUri())); // Capture the downloads here so we can verify the content. File downloads = temporaryFolder.newFolder(); opts.setDownloads(downloads); opts.setLocations(Collections.singletonList(pomFile.getAbsolutePath())); // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc. Main finishedMain = run(opts); assertThat("Errors should be empty!", finishedMain.getErrors().isEmpty(), equalTo(true)); // get the ProjectVersion info by pomPath reading from ArtifactPathInfo parse. ArtifactPathInfo artifactPathInfo = ArtifactPathInfo.parse(pomPath); ProjectVersionRef gav = artifactPathInfo.getProjectId(); File metadataFile = Paths.get(opts.getDownloads().getAbsolutePath(), gav.getGroupId().replace('.', File.separatorChar), gav.getArtifactId(), "maven-metadata.xml") .toFile(); assertThat("maven-metadata.xml for path: " + metadataFile.getParent() + " doesn't seem to have been generated!", metadataFile.exists(), equalTo(true)); }
From source file:forge.deck.io.DeckGroupSerializer.java
@Override protected final DeckGroup read(final File file) { final Deck humanDeck = DeckSerializer.fromFile(new File(file, humanDeckFile)); if (humanDeck == null) { return null; }/* w ww . ja va2s. c om*/ final DeckGroup d = new DeckGroup(humanDeck.getName()); d.setDirectory(file.getParent().substring(rootDir.length())); d.setHumanDeck(humanDeck); for (int i = 1; i < DeckGroupSerializer.MAX_DRAFT_PLAYERS; i++) { final File theFile = new File(file, "ai-" + i + ".dck"); if (!theFile.exists()) { break; } d.addAiDeck(DeckSerializer.fromFile(theFile)); } return d; }
From source file:com.bibisco.manager.ProjectManager.java
public static void unZipIt(String pStrZipFile) { mLog.debug("Start unZipIt(String)"); try {// ww w. j av a2s.c o m // get temp directory path String lStrTempDirectory = ContextManager.getInstance().getTempDirectoryPath(); // get the zip file content ZipInputStream lZipInputStream = new ZipInputStream(new FileInputStream(pStrZipFile)); // get the zipped file list entry ZipEntry lZipEntry = lZipInputStream.getNextEntry(); while (lZipEntry != null) { String lStrFileName = lZipEntry.getName(); File lFileZipEntry = new File(lStrTempDirectory + File.separator + lStrFileName); // create all non exists folders new File(lFileZipEntry.getParent()).mkdirs(); FileOutputStream lFileOutputStream = new FileOutputStream(lFileZipEntry); byte[] buffer = new byte[1024]; int lIntLen; while ((lIntLen = lZipInputStream.read(buffer)) > 0) { lFileOutputStream.write(buffer, 0, lIntLen); } lFileOutputStream.close(); lZipEntry = lZipInputStream.getNextEntry(); } lZipInputStream.closeEntry(); lZipInputStream.close(); } catch (IOException e) { mLog.error(e); throw new BibiscoException(e, BibiscoException.IO_EXCEPTION); } mLog.debug("End unZipIt(String)"); }
From source file:com.terradue.dsi.UploadAppliance.java
private File md5(File file) throws IOException { logger.info("Creating MD5 chescksum for file {}...", file); File checksumFile = new File(file.getParent(), format("%s.md5", file.getName())); InputStream data = new FileInputStream(file); try {//from w w w.ja v a 2 s . c o m String md5 = md5Hex(data); logger.info("MD5 ({}) = {}", file.getName(), md5); write(checksumFile, format("%s %s", md5, file.getName())); } finally { closeQuietly(data); } return checksumFile; }
From source file:de.hybris.platform.acceleratorservices.dataimport.batch.task.ImpexTransformerTask.java
/** * Returns the impex file/* w w w .ja v a2 s.co m*/ * * @param file * @param position * file position * @return the impex file */ protected File getImpexFile(final File file, final int position) { return new File(file.getParent(), IMPEX_FILE_PREFIX + position + "_" + file.getName()); }