List of usage examples for java.io FileWriter write
public void write(int c) throws IOException
From source file:com.jgui.ttscrape.htmlunit.FetchController.java
protected void writeShows(List<Show> shows, String filename) throws IOException { if (shows != null) { File f = new File("results/" + filename); f.getParentFile().mkdirs();/* ww w. j a v a 2 s . c o m*/ FileWriter showwriter = new FileWriter(f); for (Show s : shows) { showwriter.write(s.toString());// s.format()); showwriter.write("\n"); } showwriter.close(); } }
From source file:com.dmsl.anyplace.tasks.FetchFloorPlanTask.java
@Override protected String doInBackground(Void... params) { OutputStream output = null;//from w w w . j a va 2s . com InputStream is = null; File tempFile = null; try { // check sdcard state if (!AndroidUtils.checkExternalStorageState()) { // we cannot download the floor plan on the sdcard return "Error: It seems that we cannot write on your sdcard!"; } File sdcard_root = ctx.getExternalFilesDir(null); if (sdcard_root == null) { return "Error: It seems we cannot save the floorplan on sdcard!"; } File root = new File(sdcard_root, "floor_plans" + File.separatorChar + buid + File.separatorChar + floor_number); root.mkdirs(); File dest_path = new File(root, "tiles_archive.zip"); File okfile = new File(root, "ok.txt"); // check if the file already exists and if yes return // immediately if (dest_path.exists() && dest_path.canRead() && dest_path.isFile() && okfile.exists()) { floor_plan_file = dest_path; success = true; return "Successfully read floor plan from cache!"; } runPreExecuteOnUI(); okfile.delete(); // prepare the json object request JSONObject j = new JSONObject(); j.put("username", "username"); j.put("password", "pass"); is = NetworkUtils.downloadHttpClientJsonPostStream( AnyplaceAPI.getServeFloorTilesZipUrl(buid, floor_number), j.toString()); tempFile = new File(ctx.getCacheDir(), "FloorPlan" + Integer.toString((int) (Math.random() * 100))); if (tempFile.exists()) throw new Exception("Temp File already in use"); output = new FileOutputStream(tempFile); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = is.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, bytesRead); } output.close(); // Critical Block - Added for safety synchronized (sync) { copy(tempFile, dest_path); // unzip the tiles_archive AndroidUtils.unzip(dest_path.getAbsolutePath()); FileWriter out = new FileWriter(okfile); out.write("ok;version:0;"); out.close(); } floor_plan_file = dest_path; waitPreExecute(); success = true; return "Successfully fetched floor plan"; } catch (ConnectTimeoutException e) { return "Cannot connect to Anyplace service!"; } catch (SocketTimeoutException e) { return "Communication with the server is taking too long!"; } catch (JSONException e) { return "JSONException: " + e.getMessage(); } catch (Exception e) { return "Error fetching floor plan. [ " + e.getMessage() + " ]"; } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (output != null) try { output.close(); } catch (IOException e) { } if (tempFile != null) { tempFile.delete(); } } }
From source file:com.l2jfree.gameserver.Announcements.java
private void saveToDisk() { File file = new File("data/announcements.txt"); FileWriter save = null; try {/*from ww w. jav a2 s . co m*/ save = new FileWriter(file); for (int i = 0; i < _announcements.size(); i++) { save.write(_announcements.get(i)); save.write("\r\n"); } } catch (IOException e) { _log.warn("saving the announcements file has failed: ", e); } finally { try { if (save != null) save.close(); } catch (Exception e) { } } }
From source file:com.blackducksoftware.integration.hub.cli.CLIDownloadService.java
public void customInstall(HubProxyInfo hubProxyInfo, CLILocation cliLocation, CIEnvironmentVariables ciEnvironmentVariables, final URL archive, String hubVersion, final String localHostName) throws IOException, InterruptedException, HubIntegrationException, IllegalArgumentException, EncryptionException { boolean cliMismatch = true; try {/* ww w . j ava 2 s. c o m*/ final File hubVersionFile = cliLocation.createHubVersionFile(); if (hubVersionFile.exists()) { final String storedHubVersion = IOUtils.toString(new FileReader(hubVersionFile)); if (hubVersion.equals(storedHubVersion)) { cliMismatch = false; } else { hubVersionFile.delete(); hubVersionFile.createNewFile(); } } final File cliInstallDirectory = cliLocation.getCLIInstallDir(); if (!cliInstallDirectory.exists()) { cliMismatch = true; } if (cliMismatch) { logger.debug("Attempting to download the Hub CLI."); final FileWriter writer = new FileWriter(hubVersionFile); writer.write(hubVersion); writer.close(); hubVersionFile.setLastModified(0L); } final long cliTimestamp = hubVersionFile.lastModified(); URLConnection connection = null; try { Proxy proxy = null; if (hubProxyInfo != null) { String proxyHost = hubProxyInfo.getHost(); int proxyPort = hubProxyInfo.getPort(); String proxyUsername = hubProxyInfo.getUsername(); String proxyPassword = hubProxyInfo.getDecryptedPassword(); if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } if (proxy != null) { if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword)) { AuthenticatorUtil.setAuthenticator(proxyUsername, proxyPassword); } else { AuthenticatorUtil.resetAuthenticator(); } } } if (proxy != null) { connection = archive.openConnection(proxy); } else { connection = archive.openConnection(); } connection.setIfModifiedSince(cliTimestamp); connection.connect(); } catch (final IOException ioe) { logger.error("Skipping installation of " + archive + " to " + cliLocation.getCanonicalPath() + ": " + ioe.toString()); return; } if (connection instanceof HttpURLConnection && ((HttpURLConnection) connection).getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { // CLI has not been modified return; } final long sourceTimestamp = connection.getLastModified(); if (cliInstallDirectory.exists() && cliInstallDirectory.listFiles().length > 0) { if (!cliMismatch && sourceTimestamp == cliTimestamp) { logger.debug("The current Hub CLI is up to date."); return; } for (final File file : cliInstallDirectory.listFiles()) { FileUtils.deleteDirectory(file); } } else { cliInstallDirectory.mkdir(); } logger.debug("Updating the Hub CLI."); hubVersionFile.setLastModified(sourceTimestamp); logger.info("Unpacking " + archive.toString() + " to " + cliInstallDirectory.getCanonicalPath() + " on " + localHostName); final CountingInputStream cis = new CountingInputStream(connection.getInputStream()); try { unzip(cliInstallDirectory, cis, logger); updateJreSecurity(logger, cliLocation, ciEnvironmentVariables); } catch (final IOException e) { throw new IOException(String.format("Failed to unpack %s (%d bytes read of total %d)", archive, cis.getByteCount(), connection.getContentLength()), e); } } catch (final IOException e) { throw new IOException("Failed to install " + archive + " to " + cliLocation.getCanonicalPath(), e); } }
From source file:com.indoqa.maven.wadldoc.AbstractWadlDocumentationMojo.java
private HtmlDocument writeIndexPage(Collection<File> wadlFiles) throws MavenReportException { // XPath factory and namespace context XPathExpression expression;//from w w w . j a v a2 s . c o m try { XPath xpath = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI).newXPath(); xpath.setNamespaceContext(new WadlNamespaceContext()); expression = xpath.compile("/w:application/w:doc/@title"); } catch (Exception e) { throw new MavenReportException("Can't create xpath factory.", e); } List<HtmlDocument> htmlDocuments = new ArrayList<HtmlDocument>(); for (File wadlFile : wadlFiles) { htmlDocuments .add(new HtmlDocument(getWadlDocumentName(expression, wadlFile), createOutFileName(wadlFile))); } Collections.sort(htmlDocuments, new Comparator<HtmlDocument>() { public int compare(HtmlDocument d1, HtmlDocument d2) { return d1.getName().compareTo(d2.getName()); } }); File f = new File(this.outputDirectory, "resources.html"); FileWriter fw = null; try { fw = new FileWriter(f); fw.write(this.createIndexFileContent(htmlDocuments)); } catch (IOException e) { throw new MavenReportException("Can't create index.html", e); } finally { IOUtils.closeQuietly(fw); } return htmlDocuments.get(0); }
From source file:gobblin.example.simplejson.SimpleJsonSource.java
@Override public List<WorkUnit> getWorkunits(SourceState state) { List<WorkUnit> workUnits = Lists.newArrayList(); if (!state.contains(ConfigurationKeys.SOURCE_FILEBASED_FILES_TO_PULL)) { return workUnits; }/* w ww . ja v a2 s .com*/ // Create a single snapshot-type extract for all files Extract extract = new Extract(state, Extract.TableType.SNAPSHOT_ONLY, state.getProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, "ExampleNamespace"), "ExampleTable"); String filesToPull = state.getProp(ConfigurationKeys.SOURCE_FILEBASED_FILES_TO_PULL); File tempFileDir = new File("test_temp/"); // TODO: Delete the dir after completion. tempFileDir.mkdir(); String tempFileDirAbsolute = ""; try { tempFileDirAbsolute = tempFileDir.getCanonicalPath(); // Retrieve absolute path of temp folder } catch (IOException e) { e.printStackTrace(); } int nameCount = 0; int csvCount = 0; for (String file : Splitter.on(',').omitEmptyStrings().split(filesToPull)) { Iterator it = FileUtils.iterateFiles(new File(file), null, true); while (it.hasNext()) { try { File newFile = (File) it.next(); String basePath = newFile.getCanonicalPath(); // Retrieve absolute path of source Path path = newFile.toPath(); //call to rest api:, provide with file basePath String extension = ""; System.out.println("basePath is" + basePath); int i = basePath.lastIndexOf('.'); System.out.println("i"); if (i > 0) { extension = basePath.substring(i + 1); } String url_file_name = ""; int j = basePath.lastIndexOf('/'); if (j > 0) { url_file_name = basePath.substring(j + 1); } //hand off to rest api if (extension.equals("csv")) { System.out.println("CSVCSVCSV"); csvCount += 1; System.out.println("CURL________________________________________"); //Include basePath, filename, location you want to store file System.out.println( "curl http://localhost:8080" + basePath + "/" + Integer.toString(nameCount)); //10.0.2.2 is localhost from vagrant // Insert the nameCount so that it can be joined back later. Process p = Runtime.getRuntime() .exec("curl http://localhost:8080" + basePath + "/" + Integer.toString(nameCount)); // String myUrl = "http://localhost:8080/parse" + basePath + "&" + url_file_name + "&" + tempFileDirAbsolute; // System.out.println("------------------------------"); // System.out.println(myUrl); // try { // URL url = new URL(myUrl); // HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("GET"); // connection.connect(); // } catch (Exception e) { // e.printStackTrace(); // } } // Print filename and associated metadata System.out.println(basePath); BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class); // System.out.println(" creationTime: " + attr.creationTime()); // System.out.println(" lastAccessTime: " + attr.lastAccessTime()); // System.out.println(" lastModifiedTime: " + attr.lastModifiedTime()); // System.out.println(" isDirectory: " + attr.isDirectory()); // System.out.println(" isOther: " + attr.isOther()); // System.out.println(" isRegularFile: " + attr.isRegularFile()); // System.out.println(" isSymbolicLink: " + attr.isSymbolicLink()); // System.out.println(" size: " + attr.size()); // System.out.println(" "); //creating intermediate JSON JSONObject intermediate = new JSONObject(); intermediate.put("filename", basePath); intermediate.put("timestamp", String.valueOf((new Date()).getTime())); intermediate.put("namespace", getMacAddress()); intermediate.put("creationTime", String.valueOf(attr.creationTime())); intermediate.put("lastAccessTime", String.valueOf(attr.lastAccessTime())); intermediate.put("lastModifiedTime", String.valueOf(attr.lastModifiedTime())); intermediate.put("isDirectory", String.valueOf(attr.isDirectory())); intermediate.put("isOther", String.valueOf(attr.isOther())); intermediate.put("isRegularFile", String.valueOf(attr.isRegularFile())); intermediate.put("isSymbolicLink", String.valueOf(attr.isSymbolicLink())); intermediate.put("size", attr.size()); // Create intermediate temp file nameCount += 1; String intermediateName = "/generated" + String.valueOf(nameCount) + ".json"; String finalName = tempFileDirAbsolute + intermediateName; FileWriter generated = new FileWriter(finalName); generated.write(intermediate.toJSONString()); generated.flush(); generated.close(); // Create one work unit for each file to pull WorkUnit workUnit = new WorkUnit(state, extract); workUnit.setProp(SOURCE_FILE_KEY, finalName); workUnits.add(workUnit); } catch (IOException e) { e.printStackTrace(); } } // write out number of files found to temp file try { FileWriter numCsvFiles = new FileWriter(tempFileDirAbsolute + "/numCsvFiles.txt"); numCsvFiles.write("" + csvCount); numCsvFiles.flush(); numCsvFiles.close(); FileWriter numFiles = new FileWriter(tempFileDirAbsolute + "/numFiles.txt"); numFiles.write("" + nameCount); numFiles.flush(); numFiles.close(); } catch (IOException e) { e.printStackTrace(); } } return workUnits; }
From source file:com.cyberway.issue.util.SurtPrefixSet.java
/** * @param fw//from w w w . j a v a2 s .c om * @throws IOException */ public void exportTo(FileWriter fw) throws IOException { Iterator iter = this.iterator(); while (iter.hasNext()) { fw.write((String) iter.next() + "\n"); } }
From source file:BasicEditor.java
/** * Saves the content of the styled text to the file. If the file has * not been specified yet, a FileDialog prompts up for the user to * select a file.// w ww.j a v a 2s.co m * @return the status of the operation. * @throws IOException */ boolean saveTextToFile() { if (file == null) { FileDialog dialog = new FileDialog(shell, SWT.SAVE); if (lastOpenDirectory != null) dialog.setFilterPath(lastOpenDirectory); String selectedFile = dialog.open(); if (selectedFile == null) { log("Action cancelled: saving the text to a file"); return false; } file = new File(selectedFile); lastOpenDirectory = file.getParent(); } try { FileWriter writer = new FileWriter(file); writer.write(text.getText()); writer.close(); log("The text has been saved to file: " + file); hasUnsavedChanges = false; return true; } catch (IOException e) { log("Failed to save the text to file: " + file); log(e.toString()); } return false; }
From source file:com.axelor.studio.service.data.exporter.AsciidocExporter.java
private File exportAscci(DataReader reader, String lang, String name) { try {/*from ww w .ja v a 2s . c o m*/ File asciiDoc = File.createTempFile(name, ".txt"); FileWriter fw = new FileWriter(asciiDoc); if (lang != null && lang.equals("fr")) { fw.write(":warning-caption: Attention\n"); fw.write(":tip-caption: Astuce\n"); fw.write("= Specifications Dtailles\n:toc:\n:toclevels: 4"); } else { fw.write("= Documentation\n:toc:\n:toclevels: 4"); } processReader(reader, fw); fw.close(); return asciiDoc; } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:uk.ac.soton.itinnovation.sad.service.services.EccIntegrationService.java
public boolean start() { logger.debug("Initialising ECC Integration service"); createdProcesses = new ArrayList<>(); boolean result = true; // If ECC intagration enabled if (!configurationService.getConfiguration().isEccEnabled()) { logger.debug("Nothing to do, ECC integration disabled"); } else {/*w ww . jav a 2 s.co m*/ // Discover plugins JSONObject pluginInfo; String pathToPlugins = pluginsService.getAbsolutePluginsPath(); JSONObject currentSadConfig = JSONObject.fromObject(configurationService.getConfiguration()); String configurationFilePath; try { File tmp = File.createTempFile("sadconfiguration", ".json"); tmp.deleteOnExit(); File coordinatorPath = new File(configurationService.getConfiguration().getCoordinatorPath()); currentSadConfig.put("coordinatorPathAbs", coordinatorPath.getAbsolutePath()); FileWriter fileWriter = new FileWriter(tmp); fileWriter.write(currentSadConfig.toString()); fileWriter.close(); configurationFilePath = tmp.getAbsolutePath(); logger.debug("Stored current configuration for plugins\n" + currentSadConfig.toString(2) + "\nin: " + configurationFilePath); } catch (IOException e) { logger.error("Failed to create temporary configuration file", e); return false; } ServerSocket s; Thread tempThread; int pluginCounter = 0; for (String pluginName : pluginsService.getPluginNames()) { pluginCounter++; logger.debug("Processing plugin " + pluginCounter + ": " + pluginName); pluginInfo = pluginsService.getPluginByName(pluginName); if (pluginInfo.isEmpty()) { logger.error("Plugin not found: " + pluginName); continue; } if (!pluginInfo.containsKey("paths")) { logger.error( "Plugin configuration must contain \'paths\'. Misconfigured plugin: " + pluginName); continue; } if (!pluginInfo.containsKey("pluginFolder")) { logger.error( "Plugin configuration must be loaded with pluginsService that fills in the \'pluginFolder\' field. Misconfigured plugin: " + pluginName); continue; } JSONObject pluginPaths = pluginInfo.getJSONObject("paths"); if (!pluginPaths.containsKey("jar")) { logger.error( "Plugin configuration must contain \'paths/jar\'. Misconfigured plugin: " + pluginName); continue; } if (!pluginPaths.containsKey("dependenciesFolder")) { logger.error( "Plugin configuration must contain \'paths/dependenciesFolder\'. Misconfigured plugin: " + pluginName); continue; } if (!pluginInfo.containsKey("pluginFolder")) { logger.error("Plugin configuration must contain \'pluginFolder\'. Misconfigured plugin: " + pluginName); continue; } // portNumber++; String jarPath = pluginPaths.getString("jar"); String dependenciesFolderPath = pluginPaths.getString("dependenciesFolder"); String pluginFolder = pluginInfo.getString("pluginFolder"); String port = null; try { s = new ServerSocket(0); port = Integer.toString(s.getLocalPort()); s.close(); } catch (IOException ex) { logger.error("Failed to assign a new free port", ex); throw new RuntimeException(ex); } String uuid = configurationService.getConfiguration().getEcc().getClientsUuuidSeed() + Integer.toHexString(pluginCounter); logger.debug("Using seeded UUID: " + uuid); logger.debug("Plugin jar path from configuration: " + jarPath + ", dependenciesFolderPath: " + dependenciesFolderPath); logger.debug("Plugin folder configuration: " + pathToPlugins); logger.debug("Socket port: " + port); logger.debug("ECC client UUID: " + uuid); String[] command = new String[] { "java", "-cp", pathToPlugins + fileSeparator + pluginFolder + fileSeparator + dependenciesFolderPath + fileSeparator + "*", "-jar", pathToPlugins + fileSeparator + pluginFolder + fileSeparator + jarPath, "ecc", configurationFilePath, port, uuid }; StringBuilder commandSb = new StringBuilder(); for (String c : command) { commandSb.append(c); commandSb.append(" "); } String commandAsString = commandSb.toString(); logger.debug("Launching ECC part of '" + pluginName + "' plugin with command: " + commandAsString + " on port: " + port); pluginNamesAndPorts.put(pluginName, port); try { Process p = Runtime.getRuntime().exec(command); tempThread = new Thread(new ProcessWatcher(p)); tempThread.start(); createdProcesses.add(p); } catch (Throwable ex) { logger.error("Failed to start ECC part of '" + pluginName + "' plugin", ex); result = false; } } } return result; }