List of usage examples for java.io File createNewFile
public boolean createNewFile() throws IOException
From source file:FileAttributesDemo.java
public static void main(String[] args) throws IOException { // Create a new file, by default canWrite=true, readonly=false File file = new File("test.txt"); if (file.exists()) { file.delete();/*from w ww.j ava 2 s . c o m*/ } file.createNewFile(); System.out.println("Before. canWrite?" + file.canWrite()); // set to read-only, atau canWrite = false */ file.setWritable(false); System.out.println("After. canWrite?" + file.canWrite()); }
From source file:json.WriteToFile.java
public static void main(String[] args) { JSONObject countryObj = new JSONObject(); countryObj.put("Name", "Kenya"); countryObj.put("Population", new Integer(430000000)); JSONArray listOfCounties = new JSONArray(); listOfCounties.add("Nairobi"); listOfCounties.add("Kiambu"); listOfCounties.add("Murang'a"); countryObj.put("Counties", listOfCounties); try {//from w w w .j av a 2 s . c om //writing to file File file = new File("/home/mars/Desktop/JsonExample1.json"); file.createNewFile(); FileWriter fw = new FileWriter(file); System.out.println("Writing JSON object to file"); System.out.println("---------------------------"); System.out.println(countryObj); fw.write(countryObj + ""); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:jsonpractice.Jsonpractice.java
public static void main(String[] args) throws IOException { JSONObject countryObj = new JSONObject(); countryObj.put("Name", "India"); countryObj.put("Population", 1000000); JSONArray listOfStates = new JSONArray(); listOfStates.add("Madhya Pradesh"); listOfStates.add("Maharastra"); listOfStates.add("Tamil Nadu"); countryObj.put("States", listOfStates); try {//from ww w. ja v a 2 s . co m File file = new File("C:\\Users\\user\\Documents\\CountryJSONFile.json"); file.createNewFile(); try (FileWriter fileWriter = new FileWriter(file)) { System.out.println("Writing JSON OBJECT to file"); System.out.println("-----------------------------"); System.out.println(countryObj); fileWriter.write(countryObj.toJSONString()); fileWriter.flush(); } catch (IOException e) { } } catch (IOException e) { } }
From source file:fi.jasoft.plugin.LibSassCompiler.java
public static void main(String[] args) throws Exception { File inputFile = new File(args[0]); File outputFile = new File(args[1]); if (!outputFile.exists()) { outputFile.createNewFile(); }/*from w w w. j a va2 s . c o m*/ File sourceMapFile = new File(args[1] + ".map"); if (!sourceMapFile.exists()) { sourceMapFile.createNewFile(); } File unpackedThemes = new File(args[2]); File unpackedInputFile = Paths .get(unpackedThemes.getCanonicalPath(), inputFile.getParentFile().getName(), inputFile.getName()) .toFile(); Compiler compiler = new Compiler(); Options options = new Options(); try { Output output = compiler.compileFile(unpackedInputFile.toURI(), outputFile.toURI(), options); FileUtils.write(outputFile, output.getCss(), StandardCharsets.UTF_8.name()); FileUtils.write(sourceMapFile, output.getSourceMap(), StandardCharsets.UTF_8.name()); } catch (CompilationException e) { outputFile.delete(); sourceMapFile.delete(); throw e; } }
From source file:comparetopics.CompareTopics.java
/** * @param args the command line arguments *///from w w w. jav a 2s.co m public static void main(String[] args) { try { File file1 = new File( "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt"); File file2 = new File( "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt"); CompareTopics compareTopics = new CompareTopics(); String[] words1 = compareTopics.getWords(file1); String[] words2 = compareTopics.getWords(file2); StringBuffer words = new StringBuffer(); File outputFile = new File("/Users/apple/Desktop/test.txt"); if (outputFile.createNewFile()) { System.out.println("Create successful: " + outputFile.getName()); } boolean hasSame = false; for (String w1 : words1) { if (!NumberUtils.isNumber(w1)) { for (String w2 : words2) { if (w1.equals(w2)) { words.append(w1); // words.append("\r\n"); words.append(" "); hasSame = true; break; } } } } if (!hasSame) { System.out.println("No same word."); } else { compareTopics.printToFile(words.toString(), outputFile); } } catch (IOException ex) { Logger.getLogger(CompareTopics.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.dopsun.msg4j.tools.CodeGen.java
/** * @param args/*from w ww . ja v a2 s . c om*/ * @throws IOException * @throws MalformedURLException * @throws ParseException */ public static void main(String[] args) throws MalformedURLException, IOException, ParseException { Options options = new Options(); options.addOption("o", "out", true, "Output file"); options.addOption("s", "src", true, "Source file"); options.addOption("l", "lang", true, "Language"); CommandLineParser cmdParser = new DefaultParser(); CommandLine cmd = cmdParser.parse(options, args); String lang = cmd.getOptionValue("lang", "Java"); String srcFile = cmd.getOptionValue("src"); String outFile = cmd.getOptionValue("out"); YamlModelSource modelSource = YamlModelSource.load(new File(srcFile).toURI().toURL()); YamlModelParser parser = YamlModelParser.create(); ModelInfo modelInfo = parser.parse(modelSource); String codeText = null; if (lang.equals("Java")) { codeText = Generator.JAVA.generate(modelInfo); } else { throw new UnsupportedOperationException("Unrecognized lang: " + lang); } if (outFile != null) { File file = new File(outFile); if (file.exists()) { file.delete(); } file.createNewFile(); Files.append(codeText, new File(outFile), Charsets.UTF_8); } else { System.out.println(codeText); } }
From source file:com.client.SoapClientApache.java
public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from w w w . j a v a 2 s . co m*/ HttpGet httpGet = new HttpGet("http://google.com/"); CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST either fully consume the response content or abort request // execution by calling CloseableHttpResponse#close(). try { System.out.println("Response for http get"); System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } finally { response1.close(); } File file = new File("temConvertRq.xml"); File fileOutXml = new File("temConvertRs.xml"); fileOutXml.createNewFile(); System.out.println("Before file entity"); FileEntity entity = new FileEntity(file, ContentType.create("text/xml", "UTF-8")); System.out.println("Before http post"); HttpPost httpPost = new HttpPost("http://www.w3schools.com/webservices/tempconvert.asmx"); httpPost.setEntity(entity); System.out.println("Entity set"); //Add headers httpPost.addHeader("SOAPAction", "http://www.w3schools.com/webservices/CelsiusToFahrenheit"); httpPost.addHeader("Host", "www.w3schools.com"); httpPost.addHeader("Content-Type", "text/xml; charset=utf-8"); //httpPost.addHeader("Content-Length", "length"); System.out.println("after headers added"); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println("before getting the response status"); System.out.println("Response Status= " + response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); String outXml = EntityUtils.toString(entity2); System.out.println("XMl Response!!!!!!!!! = " + outXml); // entity2.writeTo(System.out); //System.out.println("R // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); FileUtils.writeStringToFile(fileOutXml, outXml, "UTF-8"); } finally { response2.close(); } } finally { httpclient.close(); } }
From source file:Tester.java
public static void main(String[] args) throws Exception { final String filename = "fcl/generated.fcl"; final String[] linguisticTermNames = { "muuuuuuypeque", "muypeque", "peque", "normal", "grande", "muygrande", "muuuuygrande" }; final RegionDistributionInfo[] linguisticTerms = new RegionDistributionInfo[linguisticTermNames.length]; for (int i = 0; i < linguisticTermNames.length; ++i) linguisticTerms[i] = new RegionDistributionInfo(linguisticTermNames[i], 1.0 / (linguisticTerms.length - 1)); final boolean database = true; System.out.println("Creating dataset " + System.currentTimeMillis()); final MobileDevices mobileDevices = createDataset(database); System.out.println(mobileDevices.getMobileDevices().size()); final Map<DeviceCapability, Variable> inputVariables = new HashMap<DeviceCapability, Variable>(); final Variable realSizeVar = new Variable("real_size", Arrays.asList(linguisticTerms)); final Variable resoSizeVar = new Variable("reso_size", Arrays.asList(linguisticTerms)); inputVariables.put(DeviceCapability.real_size, realSizeVar); inputVariables.put(DeviceCapability.reso_size, resoSizeVar); final Map<String, Variable> outputVariables = new HashMap<String, Variable>(); outputVariables.put("hey", new Variable("hey", Arrays.asList(new RegionDistributionInfo("ho", 1.0 / 2), new RegionDistributionInfo("lets", 1.0 / 2), new RegionDistributionInfo("go", 1.0 / 2)))); final String rules = "// the rules \n"; final FclCreator creator = new FclCreator(); System.out.println("Creating rule file " + System.currentTimeMillis()); final WarningStore warningStore = new WarningStore(); final String fileContent = creator.createRuleFile("prueba", inputVariables, new HashMap<UserCapability, Variable>(), outputVariables, mobileDevices, rules, warningStore); warningStore.print();// w ww. j a v a2 s . c o m final File file = new File(filename); file.createNewFile(); System.out.println("Dumping the rule file " + System.currentTimeMillis()); FileUtils.writeStringToFile(file, fileContent); System.out.println("Processing the file " + System.currentTimeMillis()); final FIS fis = FIS.load(filename, true); net.sourceforge.jFuzzyLogic.rule.Variable realSize = fis.getVariable("real_size"); JFreeChart theChart = realSize.chart(false); @SuppressWarnings("unused") BufferedImage img = theChart.createBufferedImage(1000, 1000); /* FileOutputStream fos = new FileOutputStream("imagen.png"); ImageEncoder myEncoder = ImageEncoderFactory.newInstance("png"); myEncoder.encode(img, fos); fos.flush(); fos.close(); */ fis.chart(); }
From source file:io.minimum.minecraft.rbclean.RedisBungeeClean.java
public static void main(String... args) { Options options = new Options(); Option hostOption = new Option("h", "host", true, "Sets the Redis host to use."); hostOption.setRequired(true);//from w ww .j a v a 2 s. c o m options.addOption(hostOption); Option portOption = new Option("p", "port", true, "Sets the Redis port to use."); options.addOption(portOption); Option passwordOption = new Option("w", "password", true, "Sets the Redis password to use."); options.addOption(passwordOption); Option dryRunOption = new Option("d", "dry-run", false, "Performs a dry run (no data is modified)."); options.addOption(dryRunOption); CommandLine commandLine; try { commandLine = new DefaultParser().parse(options, args); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("RedisBungeeClean", options); return; } int port = commandLine.hasOption('p') ? Integer.parseInt(commandLine.getOptionValue('p')) : 6379; try (Jedis jedis = new Jedis(commandLine.getOptionValue('h'), port, 0)) { if (commandLine.hasOption('w')) { jedis.auth(commandLine.getOptionValue('w')); } System.out.println("Fetching UUID cache..."); Map<String, String> uuidCache = jedis.hgetAll("uuid-cache"); Gson gson = new Gson(); // Just in case we need it, compress everything in JSON format. if (!commandLine.hasOption('d')) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); File file = new File("uuid-cache-previous-" + dateFormat.format(new Date()) + ".json.gz"); try { file.createNewFile(); } catch (IOException e) { System.out.println("Can't write backup of the UUID cache, will NOT proceed."); e.printStackTrace(); return; } System.out.println("Creating backup (as " + file.getName() + ")..."); try (OutputStreamWriter bw = new OutputStreamWriter( new GZIPOutputStream(new FileOutputStream(file)))) { gson.toJson(uuidCache, bw); } catch (IOException e) { System.out.println("Can't write backup of the UUID cache, will NOT proceed."); e.printStackTrace(); return; } } System.out.println("Cleaning out the bird cage (this may take a while...)"); int originalSize = uuidCache.size(); for (Iterator<Map.Entry<String, String>> it = uuidCache.entrySet().iterator(); it.hasNext();) { CachedUUIDEntry entry = gson.fromJson(it.next().getValue(), CachedUUIDEntry.class); if (entry.expired()) { it.remove(); } } int newSize = uuidCache.size(); if (commandLine.hasOption('d')) { System.out.println( (originalSize - newSize) + " records would be expunged if a dry run was not conducted."); } else { System.out.println("Expunging " + (originalSize - newSize) + " records..."); Transaction transaction = jedis.multi(); transaction.del("uuid-cache"); transaction.hmset("uuid-cache", uuidCache); transaction.exec(); System.out.println("Expunging complete."); } } }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false);// w w w . j a v a2 s .c om DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new FileInputStream(new File("input.xml"))); File OutputDOM = new File("out.txt"); FileOutputStream fostream = new FileOutputStream(OutputDOM); OutputStreamWriter oswriter = new OutputStreamWriter(fostream); BufferedWriter bwriter = new BufferedWriter(oswriter); if (!OutputDOM.exists()) { OutputDOM.createNewFile(); } visitRecursively(doc, bwriter); bwriter.close(); oswriter.close(); fostream.close(); }