List of usage examples for com.google.common.io Files toString
public static String toString(File file, Charset charset) throws IOException
From source file:org.eclipse.xtext.generator.AbstractGeneratorFragment.java
/** * @since 2.7/*from w w w . j a va 2 s . co m*/ */ protected String readFileIntoString(String filename, Charset encoding) { try { String result = Files.toString(new File(filename), encoding); return result; } catch (IOException e) { throw new WrappedException(e); } }
From source file:org.codice.git.GitHandler.java
@Override public String getFileAsString(String filename) throws Exception { File fileToRead = new File(filename); if (!fileToRead.exists()) { LOGGER.finest("Absolute file " + filename + " does not exist - checking relative to git dir"); fileToRead = repo.getWorkTree(); fileToRead = new File(fileToRead, filename); }/* w ww . ja v a 2 s . co m*/ LOGGER.log(Level.FINER, "Reading commit message from {0}", fileToRead.getPath()); return Files.toString(fileToRead, Charsets.UTF_8); }
From source file:com.bsiag.geneclipsetoc.internal.GenerateEclipseTocUtility.java
public static void generate(File rootInFolder, List<String> pages, String helpPrefix, File outTocFile, File outContextsFile, List<HelpContext> inContexts) throws IOException { if (!rootInFolder.exists() || !rootInFolder.isDirectory()) { throw new IllegalStateException( "Folder rootInFolder '" + rootInFolder.getAbsolutePath() + "' not found."); }//www . ja v a2s .c o m if (pages == null || pages.isEmpty()) { throw new IllegalArgumentException("pages can not be null, it should contains at least one element"); } if (outTocFile == null) { throw new IllegalStateException("File outTocFile is not set."); } if (inContexts != null && inContexts.size() > 0 && outContextsFile == null) { throw new IllegalStateException( "File outContextsFile is not set (but there are '" + inContexts.size() + "' HelpContexts)"); } //Prepare the rootInFolder list (this will check that the files exist) List<File> inFiles = new ArrayList<File>(); for (String p : pages) { if (p != null && p.length() > 0) { inFiles.add(computeFile(rootInFolder, p)); } } //Prepare the topicFileMap (this will check that the files exist) Map<File, String> topicFileMap = new HashMap<>(); if (inContexts != null) { for (HelpContext hc : inContexts) { if (hc.getTopicPages() != null) { for (String p : hc.getTopicPages()) { topicFileMap.put(computeFile(rootInFolder, p), null); } } } } Map<Integer, OutlineItemEx> nodeMap = new HashMap<Integer, OutlineItemEx>(); for (int i = 0; i < inFiles.size(); i++) { File inFile = inFiles.get(i); String html = Files.toString(inFile, Charsets.UTF_8); String filePath = calculateFilePath(rootInFolder, inFile); Document doc = Jsoup.parse(html); computeOutlineNodes(nodeMap, doc, filePath); if (topicFileMap.containsKey(inFile)) { topicFileMap.put(inFile, findFirstHeader(doc)); } } //Loop over the topicFileMap and verify that all values are set. for (File inFile : topicFileMap.keySet()) { if (topicFileMap.get(inFile) == null) { String html = Files.toString(inFile, Charsets.UTF_8); Document doc = Jsoup.parse(html); topicFileMap.put(inFile, findFirstHeader(doc)); } } OutlineItemEx root = nodeMap.get(ROOT_LEVEL); if (root == null) { throw new IllegalStateException("No header found in the html files"); } //Compute Toc File and write it MarkupToEclipseToc eclipseToc = new MarkupToEclipseToc() { @Override protected String computeFile(OutlineItem item) { if (item instanceof OutlineItemEx && ((OutlineItemEx) item).getFilePath() != null) { return ((OutlineItemEx) item).getFilePath(); } return super.computeFile(item); } }; eclipseToc.setBookTitle(root.getLabel()); eclipseToc.setHtmlFile(root.getFilePath()); eclipseToc.setHelpPrefix(helpPrefix); String tocContent = eclipseToc.createToc(root); Files.createParentDirs(outTocFile); Files.write(tocContent, outTocFile, Charsets.UTF_8); //Compute Contexts File and write it if (inContexts != null && inContexts.size() > 0) { List<Context> outContexts = computeContexts(rootInFolder, helpPrefix, inContexts, topicFileMap); String contextsContent = ContextUtility.toXml(outContexts); Files.createParentDirs(outContextsFile); Files.write(contextsContent, outContextsFile, Charsets.UTF_8); } }
From source file:com.google.devtools.j2objc.FileProcessor.java
private void processManifestFile(String filename) { if (filename.isEmpty()) { ErrorUtil.error("no @ file specified"); return;/*from www . j a v a 2 s .c om*/ } File f = new File(filename); if (!f.exists()) { ErrorUtil.error("no such file: " + filename); return; } try { String fileList = Files.toString(f, Options.getCharset()); String[] files = fileList.split("\\s+"); // Split on any whitespace. for (String file : files) { processSourceFile(file); } } catch (IOException e) { ErrorUtil.error(e.getMessage()); } }
From source file:com.publicuhc.pluginframework.util.YamlUtil.java
/** * Loads the yaml from the harddrive//w w w .ja va2 s.c o m * * @param path the path inside the directory * @param dir the directory to check in * @return optional, present if file found, absent if not * @throws IOException * @throws InvalidConfigurationException if file failed to parse */ public static Optional<YamlConfiguration> loadYamlFromDir(String path, File dir) throws IOException, InvalidConfigurationException { Validate.notNull(path, "Path to file cannot be null"); File file = new File(dir, path); if (!file.isFile()) { return Optional.absent(); } String fileContent = Files.toString(file, Charsets.UTF_8); return Optional.of(loadYamlFromString(fileContent)); }
From source file:org.glowroot.agent.config.ConfigFileUtil.java
public static void writeToFileIfNeeded(File file, ObjectNode rootObjectNode, List<String> keyOrder, boolean logStartupMessageInstead) throws IOException { String content = writeConfigAsString(rootObjectNode, keyOrder); String existingContent = ""; if (file.exists()) { existingContent = Files.toString(file, UTF_8); if (content.equals(existingContent)) { // it's nice to preserve the correct modification stamp on the file to track when it // was last really changed return; }/*from w w w .j a v a2 s . co m*/ } if (!logStartupMessageInstead) { Files.write(content, file, UTF_8); } else if (!normalize(content).equals(normalize(existingContent))) { startupLogger.info("tried to update {} during startup but the agent is running with" + " config.readOnly=true, you can prevent this message from re-occurring by" + " manually updating the file with these contents:\n{}", file.getName(), content); } }
From source file:net.oneandone.maven.plugins.billofmaterials.ReadBillOfMaterialsMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { final File bomFile = calculateBillOfMaterialsFile(); getLog().info("Reading bill of materials from " + bomFile); try {/*from ww w.j av a 2s . c o m*/ final String qaBillOfMaterials = Files.toString(bomFile, Charsets.UTF_8); getProject().getProperties().put("qaBillOfMaterials", qaBillOfMaterials); } catch (IOException e) { getLog().warn(String.format(Locale.ENGLISH, "Could not read content '%s', did you run bill-of-materials:create?", e)); } }
From source file:com.tibco.businessworks6.sonar.plugin.file.XmlFile.java
/** * Create a temporary file without any character before the prolog and * update the following attributes in order to correctly report issues: * <ul>//www . ja v a 2s. co m * <li>lineDeltaForIssue * <li>file */ private void processCharBeforePrologInFile(Charset charset, int lineDelta) { try { String content = Files.toString(file, charset); File tempFile = File.createTempFile(file.getName(), ".tmp"); int index = content.indexOf(XML_PROLOG_START_TAG); Files.write(content.substring(index), tempFile, charset); file = tempFile; if (lineDelta > 1) { lineDeltaForIssue = lineDelta - 1; } } catch (IOException e) { LOG.warn("Unable to analyse file {}", file.getAbsolutePath(), e); } }
From source file:com.nesscomputing.migratory.loader.FileLoader.java
/** * This method loads a file from a file:/... URI. This is probably not what you are looking for. *//*from www .ja va 2 s .co m*/ @Override public String loadFile(final URI fileUri) throws IOException { final File fileLocation = new File(fileUri); if (fileLocation.exists() && fileLocation.canRead()) { if (fileLocation.isFile()) { return Files.toString(fileLocation, charset); } else { throw new MigratoryException(Reason.INTERNAL, "%s is not a file!", fileLocation); } } else { throw new MigratoryException(Reason.INTERNAL, "Can not access %s!", fileLocation); } }
From source file:com.threerings.presents.tools.GenActionScriptStreamableTask.java
@Override protected void processClass(File javaSource, Class<?> sclass) throws Exception { boolean streamable = Streamable.class.isAssignableFrom(sclass) || sclass.isEnum(); if (!streamable || InvocationMarshaller.class.isAssignableFrom(sclass) || Modifier.isInterface(sclass.getModifiers()) || ActionScriptUtils.hasOmitAnnotation(sclass)) { log("Skipping " + sclass.getName(), Project.MSG_VERBOSE); return;// www . jav a 2 s .c om } log("Generating " + sclass.getName(), Project.MSG_VERBOSE); // Read the existing file in, if it exists File outputLocation = ActionScriptUtils.createActionScriptPath(_asroot, sclass); String existing = null; if (outputLocation.exists()) { existing = Files.toString(outputLocation, Charsets.UTF_8); } // Generate the current version of the streamable StreamableClassRequirements reqs = new StreamableClassRequirements(sclass); ImportSet imports = new ImportSet(); String extendsName = ""; if (sclass.isEnum()) { imports.add("com.threerings.util.Enum"); extendsName = "Enum"; } else { imports.add(ObjectInputStream.class.getName()); imports.add(ObjectOutputStream.class.getName()); } if (!sclass.getSuperclass().equals(Object.class)) { extendsName = ActionScriptUtils.addImportAndGetShortType(sclass.getSuperclass(), false, imports); } // Read the existing file's imports in. Eclipse's import organization makes // it a pain to keep additional imports out of the GENERATED PREAMBLE section of // class, so we just merge all the imports we find. if (existing != null) { ActionScriptUtils.addExistingImports(existing, imports); } boolean isDObject = DObject.class.isAssignableFrom(sclass); if (isDObject) { imports.add("org.osflash.signals.Signal"); } Set<String> implemented = Sets.newLinkedHashSet(); for (Class<?> iface : sclass.getInterfaces()) { implemented.add(ActionScriptUtils.addImportAndGetShortType(iface, false, imports)); } List<ASField> pubFields = Lists.newArrayList(); List<ASField> protFields = Lists.newArrayList(); for (Field f : reqs.streamedFields) { int mods = f.getModifiers(); if (Modifier.isPublic(mods)) { pubFields.add(new ASField(f, imports)); } else if (Modifier.isProtected(mods)) { protFields.add(new ASField(f, imports)); } else { // don't care about private continue; } } List<ASEnum> enumFields = Lists.newArrayList(); if (sclass.isEnum()) { Object[] enums = sclass.getEnumConstants(); for (Object e : enums) { enumFields.add(new ASEnum((Enum<?>) e)); } } imports.removeGlobals(); String template = sclass.isEnum() ? "enum_as.tmpl" : "streamable_as.tmpl"; String output = mergeTemplate("com/threerings/presents/tools/" + template, "header", existing == null ? _header : "", "package", sclass.getPackage().getName(), "classname", ActionScriptUtils.toSimpleName(sclass), "importGroups", imports.toGroups(), "extends", extendsName, "implements", Joiner.on(", ").join(implemented), "superclassStreamable", reqs.superclassStreamable, "pubFields", pubFields, "enumFields", enumFields, "protFields", protFields, "dobject", isDObject); if (existing != null) { // Merge in the previously generated version output = new GeneratedSourceMerger().merge(output, existing); } writeFile(outputLocation.getAbsolutePath(), output); // generate inner enums for (Class<?> inner : sclass.getDeclaredClasses()) { if (inner.isEnum()) { processClass(javaSource, inner); } } }