List of usage examples for java.io File createNewFile
public boolean createNewFile() throws IOException
From source file:com.redhat.rhn.common.util.FileUtils.java
/** * Save a String to a file on disk using specified path. * * WARNING: This deletes the original file before it writes. * * @param contents to save to file on disk * @param path to save file to.//from ww w. j a va 2s . c o m */ public static void writeStringToFile(String contents, String path) { try { File file = new File(path); if (file.exists()) { file.delete(); } file.createNewFile(); Writer output = new BufferedWriter(new FileWriter(file)); try { output.write(contents); } finally { output.close(); } } catch (Exception e) { log.error("Error trying to write file to disk: [" + path + "]", e); throw new RuntimeException(e); } }
From source file:io.proleap.cobol.TestGenerator.java
public static void generateTreeFile(final File cobolInputFile, final File outputDirectory) throws IOException { final File outputFile = new File(outputDirectory + "/" + cobolInputFile.getName() + TREE_EXTENSION); final boolean createdNewFile = outputFile.createNewFile(); if (createdNewFile) { LOG.info("Creating tree file {}.", outputFile); final File parentDirectory = cobolInputFile.getParentFile(); final CobolSourceFormat format = getCobolSourceFormat(parentDirectory); final String preProcessedInput = CobolGrammarContext.getInstance().getCobolPreprocessor() .process(cobolInputFile, parentDirectory, format); final Cobol85Lexer lexer = new Cobol85Lexer(new ANTLRInputStream(preProcessedInput)); final CommonTokenStream tokens = new CommonTokenStream(lexer); final Cobol85Parser parser = new Cobol85Parser(tokens); final StartRuleContext startRule = parser.startRule(); final String inputFileTree = TreeUtils.toStringTree(startRule, parser); final PrintWriter pWriter = new PrintWriter(new FileWriter(outputFile)); pWriter.write(inputFileTree);// w w w. j av a 2 s.c o m pWriter.flush(); pWriter.close(); } }
From source file:com.unicornlabs.kabouter.reporting.PowerReport.java
public static void GeneratePowerReport(Date startDate, Date endDate) { try {/*from w w w . j a va 2 s. c o m*/ Historian theHistorian = (Historian) BusinessObjectManager.getBusinessObject(Historian.class.getName()); ArrayList<String> powerLogDeviceIds = theHistorian.getPowerLogDeviceIds(); Document document = new Document(PageSize.A4, 50, 50, 50, 50); File outputFile = new File("PowerReport.pdf"); outputFile.createNewFile(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); document.add(new Paragraph("Power Report for " + startDate.toString() + " to " + endDate.toString())); document.newPage(); DecimalFormat df = new DecimalFormat("#.###"); for (String deviceId : powerLogDeviceIds) { ArrayList<Powerlog> powerlogs = theHistorian.getPowerlogs(deviceId, startDate, endDate); double total = 0; double max = 0; Date maxTime = startDate; double average = 0; XYSeries series = new XYSeries(deviceId); XYDataset dataset = new XYSeriesCollection(series); for (Powerlog log : powerlogs) { total += log.getPower(); if (log.getPower() > max) { max = log.getPower(); maxTime = log.getId().getLogtime(); } series.add(log.getId().getLogtime().getTime(), log.getPower()); } average = total / powerlogs.size(); document.add(new Paragraph("\nDevice: " + deviceId)); document.add(new Paragraph("Average Power Usage: " + df.format(average))); document.add(new Paragraph("Maximum Power Usage: " + df.format(max) + " at " + maxTime.toString())); document.add(new Paragraph("Total Power Usage: " + df.format(total))); //Create a custom date axis to display dates on the X axis DateAxis dateAxis = new DateAxis("Date"); //Make the labels vertical dateAxis.setVerticalTickLabels(true); //Create the power axis NumberAxis powerAxis = new NumberAxis("Power"); //Set both axes to auto range for their values powerAxis.setAutoRange(true); dateAxis.setAutoRange(true); //Create the tooltip generator StandardXYToolTipGenerator ttg = new StandardXYToolTipGenerator("{0}: {2}", new SimpleDateFormat("yyyy/MM/dd HH:mm"), NumberFormat.getInstance()); //Set the renderer StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES, ttg, null); //Create the plot XYPlot plot = new XYPlot(dataset, dateAxis, powerAxis, renderer); //Create the chart JFreeChart myChart = new JFreeChart(deviceId, JFreeChart.DEFAULT_TITLE_FONT, plot, true); PdfContentByte pcb = writer.getDirectContent(); PdfTemplate tp = pcb.createTemplate(480, 360); Graphics2D g2d = tp.createGraphics(480, 360, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, 480, 360); myChart.draw(g2d, r2d); g2d.dispose(); pcb.addTemplate(tp, 0, 0); document.newPage(); } document.close(); JOptionPane.showMessageDialog(null, "Report Generated."); Desktop.getDesktop().open(outputFile); } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(null, "Unable To Open File For Writing, Make Sure It Is Not Currently Open"); } catch (IOException ex) { Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Main.java
public static File createFile(String path) throws IOException { if (notEmptyOrNull(path)) { File file = new File(path); if (!file.exists()) { int lastIndex = path.lastIndexOf(File.separator); String dir = path.substring(0, lastIndex); if (createFolder(dir) != null) { file.createNewFile(); return file; }//from w w w. j av a 2s.c om } else { file.createNewFile(); return file; } } return null; }
From source file:bammerbom.ultimatecore.spongeapi.resources.classes.ErrorLogger.java
public static void log(Throwable t, String s) { String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS").format(Calendar.getInstance().getTime()); File dir = new File(r.getUC().getDataFolder() + "/Errors"); if (!dir.exists()) { dir.mkdir();//from w w w . jav a2 s . c om } File file = new File(r.getUC().getDataFolder() + "/Errors", time + ".txt"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileWriter outFile; try { outFile = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } PrintWriter out = new PrintWriter(outFile); out.println("======================================="); out.println("UltimateCore has run into an error "); out.println("Please report your error on dev.bukkit.org/bukkit-plugins/ultimate_core/create-ticket"); out.println("Spongeapi version: " + r.getGame().getMinecraftVersion() + " - " + r.getGame().getImplementationVersion()); out.println("UltimateCore version: " + r.getGame().getPluginManager().getPlugin("UltimateCore").get().getVersion()); out.println("Plugins loaded (" + r.getGame().getPluginManager().getPlugins().size() + "): " + Arrays.asList(r.getGame().getPluginManager().getPlugins())); out.println("Java version: " + System.getProperty("java.version")); out.println("OS info: " + System.getProperty("os.arch") + ", " + System.getProperty("os.name") + ", " + System.getProperty("os.version")); if (r.getGame().getServer().isPresent()) { out.println("Online mode: " + r.getGame().getServer().get().getOnlineMode()); } out.println("Time: " + time); out.println("Error message: " + t.getMessage()); out.println("UltimateCore message: " + s); out.println("======================================="); out.println("Stacktrace: \n" + ExceptionUtils.getStackTrace(t)); out.println("======================================="); out.close(); try { outFile.close(); } catch (IOException e) { e.printStackTrace(); } // r.log(" "); r.log(TextColors.DARK_RED + "========================================================="); r.log(TextColors.RED + "UltimateCore has run into an error "); r.log(TextColors.RED + "Please report your error on "); r.log(TextColors.YELLOW + "http://dev.bukkit.org/bukkit-plugins/ultimate_core/create-ticket"); r.log(TextColors.RED + "Include the file: "); r.log(TextColors.YELLOW + "plugins/UltimateCore/Errors/" + time + ".txt "); /*r.log(TextColors.RED + "Sponge version: " + Bukkit.getServer().getVersion()); r.log(TextColors.RED + "UltimateCore version: " + Bukkit.getPluginManager().getPlugin("UltimateCore").getDescription().getVersion()); r.log(TextColors.RED + "Plugins loaded (" + Bukkit.getPluginManager().getPlugins().length + "): " + Arrays.asList(Bukkit.getPluginManager().getPlugins())); r.log(TextColors.RED + "Java version: " + System.getProperty("java.version")); r.log(TextColors.RED + "OS info: " + System.getProperty("os.arch") + ", " + System.getProperty("os.name") + ", " + System.getProperty("os.version")); r.log(TextColors.RED + "Error message: " + t.getMessage()); r.log(TextColors.RED + "UltimateCore message: " + s);*/ r.log(TextColors.DARK_RED + "========================================================="); if (t instanceof Exception) { r.log(TextColors.RED + "Stacktrace: "); t.printStackTrace(); r.log(TextColors.DARK_RED + "========================================================="); } r.log(" "); }
From source file:io.proleap.vb6.TestGenerator.java
public static void generateTestClass(final File vb6InputFile, final File outputDirectory, final String packageName) throws IOException { final String inputFilename = getInputFilename(vb6InputFile); final File outputFile = new File( outputDirectory + "/" + inputFilename + OUTPUT_FILE_SUFFIX + JAVA_EXTENSION); final boolean createdNewFile = outputFile.createNewFile(); if (createdNewFile) { LOG.info("Creating unit test {}.", outputFile); final PrintWriter pWriter = new PrintWriter(new FileWriter(outputFile)); final String vb6InputFileName = vb6InputFile.getPath().replace("\\", "/"); pWriter.write("package " + packageName + ";\n"); pWriter.write("\n"); pWriter.write("import java.io.File;\n"); pWriter.write("\n"); pWriter.write("import org.junit.Test;\n"); pWriter.write("import io.proleap.vb6.runner.VbParseTestRunner;\n"); pWriter.write("import io.proleap.vb6.runner.impl.VbParseTestRunnerImpl;\n"); pWriter.write("\n"); pWriter.write("public class " + inputFilename + "Test {\n"); pWriter.write("\n"); pWriter.write(" @Test\n"); pWriter.write(" public void test() throws Exception {\n"); pWriter.write(" final File inputFile = new File(\"" + vb6InputFileName + "\");\n"); pWriter.write(" final VbParseTestRunner runner = new VbParseTestRunnerImpl();\n"); pWriter.write(" runner.parseFile(inputFile);\n"); pWriter.write(" }\n"); pWriter.write("}"); pWriter.flush();/*from w w w .ja v a 2 s. c om*/ pWriter.close(); } }
From source file:com.zimbra.common.util.CliUtil.java
/** * Turns on command line editing with JLine. * @param histFilePath path to the history file, or {@code null} to not save history * @throws IOException if the history file is not writable or cannot be created *//*from www . ja va2 s . c o m*/ public static void enableCommandLineEditing(String histFilePath) throws IOException { File histFile = null; if (histFilePath != null) { histFile = new File(histFilePath); if (!histFile.exists()) { if (!histFile.createNewFile()) { throw new IOException("Unable to create history file " + histFilePath); } } if (!histFile.canWrite()) { throw new IOException(histFilePath + " is not writable"); } } ConsoleReader reader = new ConsoleReader(); if (histFile != null) { reader.setHistory(new History(histFile)); } ConsoleReaderInputStream.setIn(reader); }
From source file:com.abiquo.appliancemanager.ApplianceManagerAsserts.java
/** * /*from w ww . j a v a 2 s . c om*/ * * */ protected static void createBundleDiskFile(final String ovfId, final String snapshot) throws Exception { EnterpriseRepositoryService er = ErepoFactory.getRepo(String.valueOf(idEnterprise)); final String ovfpath = TemplateConventions.getRelativePackagePath(ovfId); final String diskFilePathRel = er.getDiskFilePath(ovfId); // final String diskFilePathRel = diskFilePath.substring(diskFilePath.lastIndexOf('/')); final String path = FilenameUtils.concat(FilenameUtils.concat(er.path(), ovfpath), (snapshot + "-snapshot-" + diskFilePathRel)); // "/opt/testvmrepo/1/rs.bcn.abiquo.com/m0n0wall/000snap000-snapshot-m0n0wall-1.3b18-i386-flat.vmdk" File f = new File(path); f.createNewFile(); f.deleteOnExit(); FileWriter fileWriter = new FileWriter(f); for (int i = 0; i < 1000; i++) { fileWriter.write(i % 1); } fileWriter.close(); }
From source file:io.treefarm.plugins.haxe.utils.HaxelibHelper.java
public static File getHaxelibDirectoryForArtifactAndInitialize(String artifactId, String version, Logger logger) {// w w w .ja v a2 s . c o m File haxelibDirectory = getHaxelibDirectoryForArtifact(artifactId, version); if (haxelibDirectory != null) { File currentFile = new File(haxelibDirectory.getParentFile(), ".current"); if (!currentFile.exists()) { try { currentFile.createNewFile(); } catch (IOException e) { logger.error("Unable to create pointer for '" + artifactId + "' haxelib: " + e); // todo: throw exception!! } } } return haxelibDirectory; }
From source file:Main.java
public static void writeInteractionInFile(Context context, String startTime, String endTime, long duration, String filename) throws IOException, Exception { BufferedWriter writer = null; //String path="sdcard/LifeTracker/lifetracker.csv"; File dir = new File("sdcard/SleepLog"); boolean flag = dir.mkdir(); //Log.d("Directory created?",""+flag); File file = new File(dir.getAbsolutePath(), filename); if (file.exists() == false) { // Intent service = new Intent(context,DataBaseService.class); // context.startService(service); file.createNewFile(); writer = new BufferedWriter(new FileWriter(file, true)); writer.write("Start Time,End Time,Duration"); writer.newLine();//from ww w .ja va 2s .c om writer.write(startTime + "," + endTime + "," + duration); } else { writer = new BufferedWriter(new FileWriter(file, true)); writer.newLine(); writer.write(startTime + "," + endTime + "," + duration); } Log.d("Appended", "True"); writer.flush(); writer.close(); }