List of usage examples for com.google.common.io Files toString
public static String toString(File file, Charset charset) throws IOException
From source file:com.github.pires.example.App.java
/** * Reads private-key from PEM file./*from w ww . ja va2s .co m*/ * * @param filename * @return the private-key text * @throws IOException * if the file can't be read */ private static String getPrivateKeyFromFile(final String filename) throws IOException { try { return Files.toString(new File(filename), Charsets.UTF_8); } catch (IOException e) { log.error("Exception reading private key from {}", filename, e); throw e; } }
From source file:com.q335.r49.squaredays.MainActivity.java
@Override public boolean onMenuItemClick(MenuItem item) { final String extStorPath = Environment.getExternalStorageDirectory() + File.separator + fEXTSTOR + File.separator;//from w w w . j a va 2s. c o m final File cmdFile = new File(extStorPath, fTASKS); final File logFile = new File(extStorPath, fLOGS); switch (item.getItemId()) { case R.id.menuItemExport: { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1); final File directory = new File(extStorPath); directory.mkdirs(); AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this); alertBuilder.setCancelable(true).setMessage("Selected files will be exported to " + extStorPath) .setNeutralButton("Commands", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { Files.write(prefs.getString(TasksFrag.prefsTasksKey, ""), cmdFile, Charsets.UTF_8); Toast.makeText(context, "Commands exported to " + extStorPath + fTASKS, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.d("SquareDays", e.toString()); Toast.makeText(context, "Export failed. Does this app have storage permission? (Settings > Apps > tracker > Permissions)", Toast.LENGTH_LONG).show(); } } }).setNegativeButton("Log entries", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { writeLogFile(); Files.copy(new File(getFilesDir(), fLOGS), logFile); Toast.makeText(context, "Log entries exported to " + extStorPath + fLOGS, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.d("SquareDays", e.toString()); Toast.makeText(context, "Export failed. Does this app have storage permission? (Settings > Apps > tracker > Permissions)", Toast.LENGTH_LONG).show(); } } }).setPositiveButton("BOTH", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { writeLogFile(); Files.copy(new File(getFilesDir(), fLOGS), logFile); Files.write(prefs.getString(TasksFrag.prefsTasksKey, ""), cmdFile, Charsets.UTF_8); Toast.makeText(context, "Commands exported to " + extStorPath + fTASKS + System.getProperty("line.separator") + "Log entries exported to " + extStorPath + fLOGS, Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.d("SquareDays", e.toString()); Toast.makeText(context, "Export failed. Does this app have storage permission? (Settings > Apps > tracker > Permissions)", Toast.LENGTH_LONG).show(); } } }).show(); return true; } case R.id.menuItemImport: { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 1); final File directory = new File(extStorPath); if (!directory.isDirectory()) Toast.makeText(context, "Import failed. " + extStorPath + "not found.", Toast.LENGTH_LONG).show(); else { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this); alertBuilder.setCancelable(true).setMessage("Importing from " + extStorPath) .setNeutralButton("commands.json", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { String jsonText = Files.toString(cmdFile, Charsets.UTF_8); if (jsonText == null) Toast.makeText(context, "Import failed: empty file", Toast.LENGTH_SHORT) .show(); else { BF.loadCommands(jsonText); Toast.makeText(context, fTASKS + " import successful", Toast.LENGTH_SHORT) .show(); } } catch (Exception e) { Log.d("SquareDays", e.toString()); Toast.makeText(context, "Import failed. Does this app have storage access? (Settings > Apps > tracker > Permissions)", Toast.LENGTH_LONG).show(); } } }).setNegativeButton("log.txt", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!logFile.exists()) Toast.makeText(context, "Import failed: log file not found", Toast.LENGTH_LONG) .show(); else { try { Files.copy(logFile, new File(getFilesDir(), "log.txt")); pushOnly(Interval.newClearTimeMsg()); pushOnly(Interval.newClearExpMess()); readLogFile(); popAll(); Toast.makeText(context, fLOGS + " import successful", Toast.LENGTH_SHORT) .show(); } catch (Exception e) { Log.d("SquareDays", e.toString()); Toast.makeText(context, "Import failed. Does this app have storage access? (Settings > Apps > tracker > Permissions)", Toast.LENGTH_LONG).show(); } } } }).setPositiveButton("Both", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { String jsonText = Files.toString(cmdFile, Charsets.UTF_8); if (jsonText == null) { Toast.makeText(context, "Import failed: empty file", Toast.LENGTH_SHORT) .show(); } else { BF.loadCommands(jsonText); Toast.makeText(context, fTASKS + " import successful", Toast.LENGTH_SHORT) .show(); } } catch (Exception e) { Log.d("SquareDays", e.toString()); Toast.makeText(context, "Import failed. Does this app have storage access? (Settings > Apps > tracker > Permissions)", Toast.LENGTH_LONG).show(); } if (!logFile.exists()) Toast.makeText(context, fLOGS + " failed: no file", Toast.LENGTH_SHORT).show(); else { try { Files.copy(logFile, new File(getFilesDir(), "log.txt")); pushOnly(Interval.newClearTimeMsg()); pushOnly(Interval.newClearExpMess()); readLogFile(); popAll(); Toast.makeText(context, fLOGS + " import successful", Toast.LENGTH_SHORT) .show(); } catch (Exception e) { Log.d("SquareDays", e.toString()); Toast.makeText(context, "Import failed. Does this app have storage access? (Settings > Apps > tracker > Permissions)", Toast.LENGTH_LONG).show(); } } } }).show(); } return true; } case R.id.menuItemClear: { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this); alertBuilder.setCancelable(true).setMessage("Really clear log?") .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { File logFile = new File(getFilesDir(), fLOGS); if (logFile.exists()) { if (logFile.delete()) { pushOnly(Interval.newClearTimeMsg()); pushOnly(Interval.newClearExpMess()); } else Log.d("SquareDays", "Log clear failed!"); } else { pushOnly(Interval.newClearTimeMsg()); pushOnly(Interval.newClearExpMess()); } popAll(); } }).show(); return true; } case R.id.menuItemHelp: { FragmentManager fm = getSupportFragmentManager(); HelpFrag helpV = HelpFrag.newInstance(); helpV.show(fm, "fragment_edit_name"); return true; } default: return super.onOptionsItemSelected(item); } }
From source file:com.google.dart.tools.debug.core.coverage.CoverageManager.java
private static List<SourceRange> parseFileLines(IFile file) throws Exception { List<SourceRange> lineRanges = Lists.newArrayList(); String contents = Files.toString(file.getLocation().toFile(), Charsets.UTF_8); int start = 0; int offset = 0; while (offset < contents.length()) { char c = contents.charAt(offset++); if (c == '\r') { continue; }/*from ww w.j ava 2 s.co m*/ if (c == '\n') { int end = offset; lineRanges.add(new SourceRange(start, end - start)); start = end; } } return lineRanges; }
From source file:org.eclipse.xtext.generator.parser.antlr.ex.ExternalAntlrLexerFragment.java
private String readFileIntoString(String filename, Charset encoding) { try {//from w w w .j a v a 2s . co m String result = Files.toString(new File(filename), encoding); return result; } catch (IOException e) { throw new WrappedException(e); } }
From source file:org.moe.idea.builder.MOEModuleBuilder.java
private void modifyGradleSettings(@NotNull File file, Module[] modules) throws IOException { StringBuilder stringBuilder = new StringBuilder(); String newLine = System.getProperty("line.separator"); String existing = Files.toString(file, Charsets.UTF_8); if (!existing.endsWith(newLine)) { stringBuilder.append(newLine);/*from w ww. jav a2 s . co m*/ } for (Module module : modules) { stringBuilder.append("include ':"); stringBuilder.append(module.getName()); stringBuilder.append("'"); stringBuilder.append(newLine); } Files.append(stringBuilder.toString(), file, Charsets.UTF_8); }
From source file:com.bjond.utilities.MiscUtils.java
/** * The file resource must be encoded in UTF-8. * //from ww w.j a va 2s.c o m * @param myClass Class associated with the resource (resource just have to in the same package as this class, I think). * @param resourceName filename of the resource. * @return Content of the file read in string. * @throws IOException If any IO error occurs reading contents from Resource. Such as the resource not found. */ public static String readContentsFromResource(@SuppressWarnings("rawtypes") Class myClass, String resourceName) throws IOException { val rsc = myClass.getResource(resourceName); val path = rsc.getPath(); val file = new File(path); return Files.toString(file, Charset.forName("UTF-8")); }
From source file:org.renyan.leveldb.impl.VersionSet.java
public void recover() throws IOException { // Read "CURRENT" file, which contains a pointer to the current manifest file File currentFile = new File(databaseDir, Filename.currentFileName()); Preconditions.checkState(currentFile.exists(), "CURRENT file does not exist"); String currentName = Files.toString(currentFile, Charsets.UTF_8); if (currentName.isEmpty() || currentName.charAt(currentName.length() - 1) != '\n') { throw new IllegalStateException("CURRENT file does not end with newline"); }//w w w . j a va 2 s .co m currentName = currentName.substring(0, currentName.length() - 1); // open file channel FileChannel fileChannel = new FileInputStream(new File(databaseDir, currentName)).getChannel(); // read log edit log Long nextFileNumber = null; Long lastSequence = null; Long logNumber = null; Long prevLogNumber = null; Builder builder = new Builder(this, current); LogReader reader = new LogReader(fileChannel, throwExceptionMonitor(), true, 0); for (Slice record = reader.readRecord(); record != null; record = reader.readRecord()) { // read version edit VersionEdit edit = new VersionEdit(record); // verify comparator // todo implement user comparator String editComparator = edit.getComparatorName(); String userComparator = internalKeyComparator.name(); Preconditions.checkArgument(editComparator == null || editComparator.equals(userComparator), "Expected user comparator %s to match existing database comparator ", userComparator, editComparator); // apply edit builder.apply(edit); // save edit values for verification below logNumber = coalesce(edit.getLogNumber(), logNumber); prevLogNumber = coalesce(edit.getPreviousLogNumber(), prevLogNumber); nextFileNumber = coalesce(edit.getNextFileNumber(), nextFileNumber); lastSequence = coalesce(edit.getLastSequenceNumber(), lastSequence); } List<String> problems = newArrayList(); if (nextFileNumber == null) { problems.add("Descriptor does not contain a meta-nextfile entry"); } if (logNumber == null) { problems.add("Descriptor does not contain a meta-lognumber entry"); } if (lastSequence == null) { problems.add("Descriptor does not contain a last-sequence-number entry"); } if (!problems.isEmpty()) { throw new RuntimeException("Corruption: \n\t" + Joiner.on("\n\t").join(problems)); } if (prevLogNumber == null) { prevLogNumber = 0L; } Version newVersion = new Version(this); builder.saveTo(newVersion); // Install recovered version finalizeVersion(newVersion); appendVersion(newVersion); manifestFileNumber = nextFileNumber; this.nextFileNumber.set(nextFileNumber + 1); this.lastSequence = lastSequence; this.logNumber = logNumber; this.prevLogNumber = prevLogNumber; }
From source file:com.feedzai.fos.impl.r.RManager.java
/** * Generate R boilerplate code to train a model. By default it will use a build in implementation using random * randomForest. Another algorithm can be used by overriding <code>RModelConfig.TRAIN_FILE</code> and * <code>RModelConfig.TRAIN_FUNCTION</code>. * * Sample generated code//from w w w . ja va 2 s . c o m * <pre> * headersfile <- '/tmp/fosrtraining8499205938185291252.instances.header' * instancesfile <- '/tmp/fosrtraining8499205938185291252.instances' * class.name <- 'class' * * categorical.features <- c( * 'A1', * 'A4', * 'A5', * 'A6', * 'A7', * 'A9', * 'A10', * 'A12', * 'A13', * 'class') * modelsavepath <- '/tmp/fosrtraining8499205938185291252.instances.model' * trainRmodel() * </pre> * * * @param config the model configuration * @param path File with the training instances * @return * @throws FOSException */ @Override public Model trainFile(ModelConfig config, String path) throws FOSException { String trainFile = config.getProperty(RModelConfig.TRAIN_FILE); String trainFunction = config.getProperty(RModelConfig.TRAIN_FUNCTION); if (trainFunction == null) { trainFunction = RModelConfig.BUILT_IN_TRAIN_FUNCTION; } String trainArguments = config.getProperty(RModelConfig.TRAIN_FUNCTION_ARGUMENTS); String trainScript = null; try { if (trainFile != null) { trainScript = Files.toString(new File(trainFile), Charsets.UTF_8); } String libraries = config.getProperty(RModelConfig.LIBRARIES); for (String library : libraries.trim().split(",")) { library = library.trim(); if (library.length() > 0) { rserve.eval(String.format("require(%1s)", library)); } } // eval optional train script if (trainScript != null) { rserve.eval(trainScript); } List<Attribute> attributes = config.getAttributes(); File modelSaveFile = new File(config.getProperty(RModelConfig.MODEL_SAVE_PATH), (new File(path).getName()) + "." + RModelConfig.MODEL_FILE_EXTENSION); config.setProperty(RModelConfig.MODEL_FILE, modelSaveFile.getAbsolutePath()); Attribute modelClass = attributes.get(config.getIntProperty(RModelConfig.CLASS_INDEX)); // load training data rserve.eval(String.format("train.data <- read.arff('%s')", path)); rserve.eval(String.format("classfn <- as.formula('%s ~ .')", rVariableName(modelClass.getName()))); rserve.eval(String.format("model <- %s(formula = classfn, data = train.data%s)", trainFunction, trainArguments != null ? ", " + trainArguments : "")); rserve.eval(String.format("save(model, file = '%1s')", modelSaveFile.getAbsolutePath())); return new ModelBinary(Files.toByteArray(modelSaveFile)); } catch (Throwable e) { throw new FOSException(e); } }
From source file:org.iq80.leveldb.impl.VersionSet.java
public void recover() throws IOException { // Read "CURRENT" file, which contains a pointer to the current manifest file File currentFile = new File(databaseDir, Filename.currentFileName()); Preconditions.checkState(currentFile.exists(), "CURRENT file does not exist"); String currentName = Files.toString(currentFile, Charsets.UTF_8); if (currentName.isEmpty() || currentName.charAt(currentName.length() - 1) != '\n') { File dir[] = databaseDir.listFiles(); for (int x = 0; x < dir.length; x++) { if (dir[x].getName().startsWith("MANIFEST")) { currentName = dir[x].getName() + "\n"; break; }/*from w ww. j a v a 2s . co m*/ } new IllegalStateException( "CURRENT file does not end with newline," + currentFile + " --> " + currentName) .printStackTrace(); } currentName = currentName.substring(0, currentName.length() - 1); // open file channel FileChannel fileChannel = new FileInputStream(new File(databaseDir, currentName)).getChannel(); try { // read log edit log Long nextFileNumber = null; Long lastSequence = null; Long logNumber = null; Long prevLogNumber = null; Builder builder = new Builder(this, current); LogReader reader = new LogReader(fileChannel, throwExceptionMonitor(), true, 0); for (Slice record = reader.readRecord(); record != null; record = reader.readRecord()) { // read version edit VersionEdit edit = new VersionEdit(record); // verify comparator // todo implement user comparator String editComparator = edit.getComparatorName(); String userComparator = internalKeyComparator.name(); Preconditions.checkArgument(editComparator == null || editComparator.equals(userComparator), "Expected user comparator %s to match existing database comparator ", userComparator, editComparator); // apply edit builder.apply(edit); // save edit values for verification below logNumber = coalesce(edit.getLogNumber(), logNumber); prevLogNumber = coalesce(edit.getPreviousLogNumber(), prevLogNumber); nextFileNumber = coalesce(edit.getNextFileNumber(), nextFileNumber); lastSequence = coalesce(edit.getLastSequenceNumber(), lastSequence); } List<String> problems = newArrayList(); if (nextFileNumber == null) { problems.add("Descriptor does not contain a meta-nextfile entry"); } if (logNumber == null) { problems.add("Descriptor does not contain a meta-lognumber entry"); } if (lastSequence == null) { problems.add("Descriptor does not contain a last-sequence-number entry"); } if (!problems.isEmpty()) { throw new RuntimeException("Corruption: \n\t" + Joiner.on("\n\t").join(problems)); } if (prevLogNumber == null) { prevLogNumber = 0L; } Version newVersion = new Version(this); builder.saveTo(newVersion); // Install recovered version finalizeVersion(newVersion); appendVersion(newVersion); manifestFileNumber = nextFileNumber; this.nextFileNumber.set(nextFileNumber + 1); this.lastSequence = lastSequence; this.logNumber = logNumber; this.prevLogNumber = prevLogNumber; } finally { fileChannel.close(); } }
From source file:com.google.javascript.jscomp.ant.CompileTask.java
@Override public void execute() { if (this.outputFile == null) { throw new BuildException("outputFile attribute must be set"); }/*from w w w . ja v a2 s . c om*/ Compiler.setLoggingLevel(Level.OFF); CompilerOptions options = createCompilerOptions(); Compiler compiler = createCompiler(options); List<SourceFile> externs = findExternFiles(); List<SourceFile> sources = findSourceFiles(); if (isStale() || forceRecompile) { log("Compiling " + sources.size() + " file(s) with " + externs.size() + " extern(s)"); Result result = compiler.compile(externs, sources, options); if (result.success) { StringBuilder source = new StringBuilder(compiler.toSource()); if (this.outputWrapperFile != null) { try { this.outputWrapper = Files.toString(this.outputWrapperFile, UTF_8); } catch (Exception e) { throw new BuildException("Invalid output_wrapper_file specified."); } } if (this.outputWrapper != null) { int pos = -1; pos = this.outputWrapper.indexOf(CommandLineRunner.OUTPUT_MARKER); if (pos > -1) { String prefix = this.outputWrapper.substring(0, pos); source.insert(0, prefix); // end of outputWrapper int suffixStart = pos + CommandLineRunner.OUTPUT_MARKER.length(); String suffix = this.outputWrapper.substring(suffixStart); source.append(suffix); } else { throw new BuildException("Invalid output_wrapper specified. " + "Missing '" + CommandLineRunner.OUTPUT_MARKER + "'."); } } if (result.sourceMap != null) { flushSourceMap(result.sourceMap); source.append(System.getProperty("line.separator")); source.append("//# sourceMappingURL=" + sourceMapOutputFile.getName()); } writeResult(source.toString()); } else { throw new BuildException("Compilation failed."); } } else { log("None of the files changed. Compilation skipped."); } }