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.apache.flink.api.java.tuple.TupleGenerator.java
private static void insertCodeIntoFile(String code, File file) throws IOException { String fileContent = Files.toString(file, StandardCharsets.UTF_8); try (Scanner s = new Scanner(fileContent)) { StringBuilder sb = new StringBuilder(); String line;/*from w ww .ja va 2s . c o m*/ boolean indicatorFound = false; // add file beginning while (s.hasNextLine() && (line = s.nextLine()) != null) { sb.append(line).append("\n"); if (line.contains(BEGIN_INDICATOR)) { indicatorFound = true; break; } } if (!indicatorFound) { System.out.println("No indicator found in '" + file + "'. Will skip code generation."); s.close(); return; } // add generator signature sb.append("\t// GENERATED FROM ").append(TupleGenerator.class.getName()).append(".\n"); // add tuple dependent code sb.append(code).append("\n"); // skip generated code while (s.hasNextLine() && (line = s.nextLine()) != null) { if (line.contains(END_INDICATOR)) { sb.append(line).append("\n"); break; } } // add file ending while (s.hasNextLine() && (line = s.nextLine()) != null) { sb.append(line).append("\n"); } s.close(); Files.write(sb.toString(), file, StandardCharsets.UTF_8); } }
From source file:com.facebook.presto.cli.ConsoleOld.java
@Override public void run() { ClientSession session = clientOptions.toClientSession(); boolean hasQuery = !Strings.isNullOrEmpty(clientOptions.execute); boolean isFromFile = !Strings.isNullOrEmpty(clientOptions.file); if (!hasQuery || !isFromFile) { AnsiConsole.systemInstall();//from w w w .j av a2s . c om } initializeLogging(session.isDebug()); String query = clientOptions.execute; if (isFromFile) { if (hasQuery) { throw new RuntimeException("both --execute and --file specified"); } try { query = Files.toString(new File(clientOptions.file), Charsets.UTF_8); hasQuery = true; } catch (IOException e) { throw new RuntimeException( format("Error reading from file %s: %s", clientOptions.file, e.getMessage())); } } try (QueryRunner queryRunner = QueryRunner.create(session)) { if (hasQuery) { executeCommand(queryRunner, query, clientOptions.outputFormat); } else { runConsole(queryRunner, session); } } }
From source file:org.jclouds.vagrant.internal.VagrantCliFacade.java
@Override public LoginCredentials sshConfig(String machineName) { SshConfig sshConfig = vagrant.sshConfig(machineName); LoginCredentials.Builder loginCredentialsBuilder = LoginCredentials.builder().user(sshConfig.getUser()); try {/*from ww w .j a va 2 s . c om*/ String privateKey = Files.toString(new File(sshConfig.getIdentityFile()), Charset.defaultCharset()); loginCredentialsBuilder.privateKey(privateKey); } catch (IOException e) { throw new IllegalStateException("Invalid private key " + sshConfig.getIdentityFile(), e); } return loginCredentialsBuilder.build(); }
From source file:zotmc.collect.forge.McCollectInit.java
@EventHandler public void preInit(FMLPreInitializationEvent event) { try {/*from w w w .j a v a 2 s.c om*/ File dir = new File(event.getModConfigurationDirectory(), MODID); if (dir.exists() && !dir.isDirectory()) dir.delete(); dir.mkdirs(); Joiner slash = Joiner.on('/'); for (File f : dir.listFiles()) try { String fn = f.getName(); if (fn.toLowerCase(ENGLISH).endsWith(".js")) scripts.put(fn, Files.toString(f, Charsets.UTF_8)); else if (fn.toLowerCase(ENGLISH).endsWith(".zip")) { Closer closer = Closer.create(); try { ZipFile zf = new ZipFile(f); closer.register(zf); for (ZipEntry ze : Enumerable.forZipFile(zf)) if (ze.getName().toLowerCase(ENGLISH).endsWith(".js")) { String zen = slash.join(fn, ze.getName()); try { scripts.put(zen, CharStreams.toString( new InputStreamReader(zf.getInputStream(ze), Charsets.UTF_8))); } catch (Exception e) { FMLLog.log(ERROR, e, "[%s] An error occurred while reading a file: %s", NAME, zen); } } } catch (Exception e) { throw e; } finally { closer.close(); } } } catch (Exception e) { FMLLog.log(ERROR, e, "[%s] An error occurred while reading a file: %s", NAME, f.getName()); } } catch (Exception e) { FMLLog.log(ERROR, e, "[%s] An error occurred while trying to access the setting files!", NAME); } }
From source file:org.xmlsh.aws.gradle.lambda.AWSLambdaInvokeTask.java
private void setupPayload(InvokeRequest request) throws IOException { Object payload = getPayload(); String str;//from w ww . j ava2s . c om if (payload instanceof ByteBuffer) { request.setPayload((ByteBuffer) payload); return; } if (payload instanceof File) { File file = (File) payload; str = Files.toString(file, Charsets.UTF_8); } else if (payload instanceof Closure) { Closure<?> closure = (Closure<?>) payload; str = closure.call().toString(); } else { str = payload.toString(); } request.setPayload(str); }
From source file:org.jclouds.vagrant.internal.BoxConfig.java
protected BoxConfig(File vagrantHome, String name, String version, String provider) { File boxes = new File(vagrantHome, VagrantConstants.VAGRANT_BOXES_SUBFOLDER); File boxPath = new File(boxes, name.replace("/", VagrantConstants.ESCAPE_SLASH)); File versionPath = new File(boxPath, version); File providerPath = new File(versionPath, provider); File vagrantfilePath = new File(providerPath, VagrantConstants.VAGRANTFILE); if (!vagrantfilePath.exists()) { throw new IllegalStateException("Vagrantfile for box '" + name + "'" + " at " + vagrantfilePath.getAbsolutePath() + " not found"); }/* www .j a v a 2 s. c o m*/ try { config = Files.toString(vagrantfilePath, Charsets.UTF_8); } catch (IOException e) { throw new IllegalStateException( "Failure reading box '" + name + "'" + " at " + vagrantfilePath.getAbsolutePath(), e); } this.providerPath = providerPath; }
From source file:com.ferusgrim.gradletodo.TodoOutputTask.java
@TaskAction public void run() throws IOException { final PatternSet patternSet = new PatternSet(); patternSet.setIncludes(this.input.getIncludes()); patternSet.setExcludes(this.input.getExcludes()); for (final DirectoryTree dirTree : this.input.getSrcDirTrees()) { final File dir = dirTree.getDir(); if (!dir.exists() || !dir.isDirectory()) { continue; }/*from w w w. j a va 2 s .c o m*/ final FileTree tree = this.getProject().fileTree(dir).matching(this.input.getFilter()) .matching(patternSet); for (final File file : tree) { final Map<Integer, String> matches = this.getFileMatches(Files.toString(file, Charsets.UTF_8)); if (!matches.isEmpty()) { System.out.println(); LOGGER.warn("{} TODO{} found in `{}`", matches.size(), matches.size() == 1 ? "" : "s", file.getName()); for (final Map.Entry<Integer, String> match : matches.entrySet()) { LOGGER.warn("L{}: {}", match.getKey(), match.getValue().trim()); } } } } }
From source file:org.sonar.gherkin.checks.EndLineCharactersCheck.java
private boolean fileContainsIllegalEndLineCharacters() { try {//w w w. j a v a2s . c om String fileContent = Files.toString(getContext().getFile(), charset); return "CR".equals(endLineCharacters) && Pattern.compile("(?s)\n").matcher(fileContent).find() || "LF".equals(endLineCharacters) && Pattern.compile("(?s)\r").matcher(fileContent).find() || "CRLF".equals(endLineCharacters) && Pattern.compile("(?s)(\r(?!\n)|(?<!\r)\n)").matcher(fileContent).find(); } catch (IOException e) { throw new IllegalStateException( "Check gherkin:" + this.getClass().getAnnotation(Rule.class).key() + ": File cannot be read.", e); } }
From source file:com.android.tools.idea.rendering.GutterIconCache.java
@Nullable private static Icon createXmlIcon(@NotNull String path, @Nullable ResourceResolver resolver) { try {//from w w w.j a v a 2 s .c o m boolean isRetina = ourRetinaEnabled && UIUtil.isRetina(); VdPreview.TargetSize imageTargetSize = VdPreview.TargetSize .createSizeFromWidth(isRetina ? 2 * MAX_WIDTH : MAX_WIDTH); String xml = Files.toString(new File(path), Charsets.UTF_8); // See if this drawable is a vector; we can't render other drawables yet. // TODO: Consider resolving selectors to render for example the default image! if (xml.contains("<vector")) { Document document = XmlUtils.parseDocumentSilently(xml, true); if (document == null) { return null; } Element root = document.getDocumentElement(); if (root == null) { return null; } if (resolver != null) { replaceResourceReferences(root, resolver); } StringBuilder builder = new StringBuilder(100); BufferedImage image = VdPreview.getPreviewFromVectorDocument(imageTargetSize, document, builder); if (builder.length() > 0) { LOG.warn("Problems rendering " + path + ": " + builder); } if (image != null) { if (isRetina) { // The Retina image uses a scale of 2, and the RetinaImage class creates an // image of size w/scale, h/scale. If the width or height is less than the scale, // this rounds to width or height 0, which will cause exceptions to be thrown. // Don't attempt to create a Retina image for images like that. See issue 65676. final int scale = 2; if (image.getWidth() >= scale && image.getHeight() >= scale) { try { @SuppressWarnings("ConstantConditions") Image hdpiImage = RetinaImage.createFrom(image, scale, null); return new RetinaImageIcon(hdpiImage); } catch (Throwable t) { // Can't always create Retina images (see issue 65609); fall through to non-Retina code path ourRetinaEnabled = false; } } } return new ImageIcon(image); } } } catch (Throwable e) { LOG.warn(String.format("Could not read/render icon image %1$s", path), e); } return null; }
From source file:com.google.dart.tools.core.html.HtmlBuildParticipant.java
protected void processHtml(IFile file) { try {/*from w ww . ja v a 2 s.c o m*/ MarkerUtilities.deleteMarkers(file); XmlDocument document = new HtmlParser(Files.toString(file.getLocation().toFile(), Charsets.UTF_8)) .parse(); validate(document, file); } catch (CoreException e) { DartCore.logError(e); } catch (IOException ioe) { } }