com.google.common.io.CharStreams#copy ( )源码实例Demo

下面列出了com.google.common.io.CharStreams#copy ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ipst   文件: HistoDbPrintForecastDiffTool.java
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
    OfflineConfig config = OfflineConfig.load();
    try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create()) {
        Interval interval = Interval.parse(line.getOptionValue("interval"));
        try (Reader reader = new InputStreamReader(histoDbClient.queryCsv(
                HistoQueryType.forecastDiff,
                EnumSet.allOf(Country.class),
                EnumSet.of(HistoDbEquip.loads, HistoDbEquip.gen),
                EnumSet.of(HistoDbAttr.P),
                interval,
                HistoDbHorizon.DACF,
                false,
                false))) {
            CharStreams.copy(reader, context.getOutputStream());
        }
    }
}
 
源代码2 项目: proctor   文件: UtilMethods.java
static Proctor getProctor(final String matrixfilename, final String specificationFilename) {
    try {
        // just read from the resource .json file at the moment.ProctorUtils.java

        final Reader matrixResource = new BufferedReader(new InputStreamReader(TestUnitTestGroupsManager.class.getResourceAsStream(matrixfilename)));
        final String matrixString;
        try (StringWriter matrixStringWriter = new StringWriter()) {
            CharStreams.copy(matrixResource, matrixStringWriter);
            matrixString = matrixStringWriter.toString();
        }

        final ProctorSpecification specification = getProctorSpecification(specificationFilename);
        final StringProctorLoader loader = new StringProctorLoader(specification, matrixfilename, matrixString);

        assertTrue("StringProctorLoader should load", loader.load());
        return loader.get();
    } catch (final IOException e) {
        throw new RuntimeException(e);

    }
}
 
源代码3 项目: util   文件: PosixFileOperations.java
public static long du(File path) throws IOException {
    Process proc = Runtime.getRuntime().exec(new String[]{"du", "-bs", path.getPath()});
    try {
        int result = proc.waitFor();
        if (result != 0) {
            throw new IOException(
                    formatWithStdStreams(
                            proc,
                            "error running du -bs "+path.getPath()+", exit code: " + result + "\nstdout:\n%s\nstderr:\n%s"
                    ));
        }
        StringWriter out = new StringWriter();
        CharStreams.copy(new InputStreamReader(proc.getInputStream(), Charsets.UTF_8), out);
        final String str = out.toString().trim();
        final int index = str.indexOf('\t');
        return Long.parseLong(str.substring(0, index));
    } catch (InterruptedException e) {
        log.error("exception during exec", e);
        throw new IOException("exec failed", e);
    }
}
 
源代码4 项目: util   文件: PosixFileOperations.java
public static String lsla(File file) throws IOException {
    Process proc = Runtime.getRuntime().exec(new String[]{"ls", "-la"}, null, file);
    try {
        final int result = proc.waitFor();
        if (result != 0) {
            throw new IOException(
                    formatWithStdStreams(
                            proc,
                            "error running ls -la process, exit code: " + result + "\nstdout:\n%s\nstderr:\n%s"
                    )
            );
        }
        final StringWriter out = new StringWriter();
        CharStreams.copy(new InputStreamReader(proc.getInputStream(), Charsets.UTF_8), out);
        return out.toString();
    } catch (InterruptedException e) {
        log.error("exception during exec", e);
        throw new IOException("exec failed", e);
    }
}
 
源代码5 项目: neoscada   文件: DebianHandler.java
/**
 * This method scoops up all package scripts and create the calls in the
 * corresponding package scripts
 *
 * @throws IOException
 */
private String createUserScriptCallbacks ( final File packageFolder, final String type ) throws IOException
{
    final File dir = new File ( packageFolder, "src" + CONTROL_SCRIPTS_DIR + "/" + getPackageName () + "/" + type ); //$NON-NLS-1$ //$NON-NLS-2$

    if ( !dir.isDirectory () )
    {
        return "";
    }

    final StringWriter sw = new StringWriter ();
    final Charset cs = Charset.forName ( "UTF-8" );

    final File[] files = dir.listFiles ();
    Arrays.sort ( files );
    for ( final File file : files )
    {
        if ( !file.isFile () )
        {
            continue;
        }

        sw.write ( String.format ( "# ================== START - %s ==================\n", file ) );

        try ( Reader reader = Files.newBufferedReader ( file.toPath (), cs ) )
        {
            CharStreams.copy ( reader, sw );
        }

        sw.write ( String.format ( "# ==================  END - %s  ==================\n", file ) );

        file.setExecutable ( true );
    }

    return sw.toString ();
}
 
源代码6 项目: neoscada   文件: CommonPackageDeploymentContext.java
@Override
public void addPostInstallationScript ( final Reader reader ) throws IOException
{
    try
    {
        CharStreams.copy ( reader, this.postInstallation );
    }
    finally
    {
        reader.close ();
    }
}
 
源代码7 项目: neoscada   文件: CommonPackageDeploymentContext.java
@Override
public void addPreInstallationScript ( final Reader reader ) throws IOException
{
    try
    {
        CharStreams.copy ( reader, this.preInstallation );
    }
    finally
    {
        reader.close ();
    }
}
 
源代码8 项目: h2o-2   文件: Boot.java
public String loadContent(String fromFile) {
  BufferedReader reader = null;
  StringBuilder sb = new StringBuilder();
  try {
    InputStream is = getResource2(fromFile);
    reader = new BufferedReader(new InputStreamReader(is));
    CharStreams.copy(reader, sb);
  } catch( IOException e ){
    Log.err(e);
  } finally {
    Closeables.closeQuietly(reader);
  }
  return sb.toString();
}
 
源代码9 项目: neoscada   文件: CommonPackageDeploymentContext.java
@Override
public void addPreRemovalScript ( final Reader reader ) throws IOException
{
    try
    {
        CharStreams.copy ( reader, this.preRemoval );
    }
    finally
    {
        reader.close ();
    }
}
 
源代码10 项目: ipst   文件: HistoDbPrintAttributesTool.java
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
    OfflineConfig config = OfflineConfig.load();
    try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create()) {
        boolean statistics = line.hasOption("statistics");
        Set<HistoDbAttributeId> attrs = new LinkedHashSet<>();
        if (!statistics && line.hasOption("add-datetime")) {
            attrs.add(HistoDbMetaAttributeId.datetime);
        }
        for (String str : line.getOptionValue("attributes").split(",")) {
            attrs.add(HistoDbAttributeIdParser.parse(str));
        }
        Interval interval = Interval.parse(line.getOptionValue("interval"));
        boolean format = line.hasOption("format");
        HistoDbHorizon horizon = HistoDbHorizon.SN;
        if (line.hasOption("horizon")) {
            horizon = HistoDbHorizon.valueOf(line.getOptionValue("horizon"));
        }
        boolean async = false;
        boolean zipped = false;
        InputStream is = histoDbClient.queryCsv(statistics ? HistoQueryType.stats : HistoQueryType.data, attrs, interval, horizon, zipped, async);
        if (format) {
            format(is, zipped, context.getOutputStream());
        } else {
            try (Reader reader = createReader(is, zipped)) {
                CharStreams.copy(reader, context.getOutputStream());
            }
        }
    }
}
 
源代码11 项目: brooklyn-server   文件: Streams.java
public static void copy(Reader input, Writer output) {
    try {
        CharStreams.copy(input, output);
        output.flush();
    } catch (IOException ioe) {
        throw Exceptions.propagate(ioe);
    }
}
 
源代码12 项目: divolte-collector   文件: MincodeParserTest.java
@Test
public void testOnlyReadWhatIsRequired() throws IOException {
    final Reader reader = new StringReader("sA string record!Extra trailing data.");
    final JsonParser parser = MAPPER.getFactory().createParser(reader);
    assertEquals("A string record", MAPPER.readValue(parser, String.class));

    // Check the trailing data can be retrieved.
    final StringWriter writer = new StringWriter();
    parser.releaseBuffered(writer);
    assertTrue(0 < writer.getBuffer().length());
    CharStreams.copy(reader, writer);

    // Check the trailer could be retrieved.
    assertEquals("Extra trailing data.", writer.toString());
}
 
源代码13 项目: maven-framework-project   文件: GuavaTutorial.java
/**
 * 将读取的内容拷贝到一个writer中去
 * @throws Exception
 */
@Test
public void example7() throws Exception{
	File file = new File("src/main/resources/sample.txt");
	StringWriter writer = new StringWriter();
	FileWriter fileWriter = new FileWriter(new File("src/main/resources/sample-copy.txt"));
	CharStreams.copy(new FileReader(file), fileWriter);//写文件
	fileWriter.flush();
	fileWriter.close();
	System.out.println(writer.toString());
}
 
源代码14 项目: onos   文件: YangToolUtil.java
/**
 * Converts UTF-8 CompositeStream into CharSequence.
 *
 * @param utf8Input to convert
 * @return CharSequence
 */
public static CharSequence toCharSequence(CompositeStream utf8Input) {
    StringBuilder s = new StringBuilder();
    try {
        CharStreams.copy(new InputStreamReader(utf8Input.resourceData(), UTF_8), s);
        return s;
    } catch (IOException e) {
        log.error("Exception thrown", e);
        return null;
    }
}
 
源代码15 项目: Bastion   文件: ResponsePrinter.java
private void writeEntitySection(Writer writer) throws IOException {
    InputStreamReader entity = new InputStreamReader(response.getBody());
    CharStreams.copy(entity, writer);
}
 
@Override
protected void loadEntries(final StorageAwareResource resource, final ZipInputStream zipIn) throws IOException {
  ZipPositioner positioner = new ZipPositioner(zipIn);
  // 1. resource contents
  switch (mode.instruction(Constituent.CONTENT)) {
  case SKIP:
    break;
  case PROXY:
    LOG.warn("Proxying of resource contents is not supported: " + resource.getURI()); //$NON-NLS-1$
    // fall through
  case LOAD:
    positioner.position(Constituent.CONTENT);
    readContents(resource, new BufferedInputStream(zipIn));
    break;
  }

  // 2. associations adapter
  switch (mode.instruction(Constituent.ASSOCIATIONS)) {
  case SKIP:
    break;
  case PROXY:
    ProxyModelAssociationsAdapter.install(resource);
    break;
  default:
    positioner.position(Constituent.ASSOCIATIONS);
    readAssociationsAdapter(resource, new BufferedInputStream(zipIn));
    break;
  }

  // 3. source
  String content = null;
  switch (mode.instruction(Constituent.SOURCE)) {
  case SKIP:
  case PROXY:
    if (mode.instruction(Constituent.NODE_MODEL) == Instruction.LOAD) {
      throw new IllegalArgumentException("Loading node model also requires loading source"); //$NON-NLS-1$
    }
    break;
  case LOAD:
    positioner.position(Constituent.SOURCE);
    StringBuilder out = new StringBuilder(SOURCE_BUFFER_CAPACITY);
    CharStreams.copy(new InputStreamReader(zipIn, StandardCharsets.UTF_8), out);
    content = out.toString();
    break;
  }

  // 4. node model
  switch (mode.instruction(Constituent.NODE_MODEL)) {
  case SKIP:
    break;
  case PROXY:
    ProxyCompositeNode.installProxyNodeModel(resource);
    break;
  case LOAD:
    positioner.position(Constituent.NODE_MODEL);
    readNodeModel(resource, new BufferedInputStream(zipIn), content);
    break;
  }
}
 
源代码17 项目: java-client   文件: NewAppiumSessionPayload.java
private NewAppiumSessionPayload(Reader source, boolean forceMobileJSONWP) throws IOException {
    this.forceMobileJSONWP = forceMobileJSONWP;
    // Dedicate up to 10% of all RAM or 20% of available RAM (whichever is smaller) to storing this
    // payload.
    int threshold = (int) Math.min(
            Integer.MAX_VALUE,
            Math.min(
                    Runtime.getRuntime().freeMemory() / 5,
                    Runtime.getRuntime().maxMemory() / 10));

    backingStore = new FileBackedOutputStream(threshold);
    try (Writer writer = new OutputStreamWriter(backingStore, UTF_8)) {
        CharStreams.copy(source, writer);
    }

    ImmutableSet.Builder<CapabilitiesFilter> adapters = ImmutableSet.builder();
    ServiceLoader.load(CapabilitiesFilter.class).forEach(adapters::add);
    adapters
            .add(new ChromeFilter())
            .add(new EdgeFilter())
            .add(new FirefoxFilter())
            .add(new InternetExplorerFilter())
            .add(new OperaFilter())
            .add(new SafariFilter());
    this.adapters = adapters.build();

    ImmutableSet.Builder<CapabilityTransform> transforms = ImmutableSet.builder();
    ServiceLoader.load(CapabilityTransform.class).forEach(transforms::add);
    transforms
            .add(new ProxyTransform())
            .add(new StripAnyPlatform())
            .add(new W3CPlatformNameNormaliser());
    this.transforms = transforms.build();

    ImmutableSet.Builder<Dialect> dialects = ImmutableSet.builder();
    if (getOss() != null) {
        dialects.add(Dialect.OSS);
    }
    if (getAlwaysMatch() != null || getFirstMatch() != null) {
        dialects.add(Dialect.W3C);
    }

    validate();
}
 
源代码18 项目: buck   文件: TraceDataHandler.java
private void doGet(Request baseRequest, HttpServletResponse response) throws IOException {
  String path = baseRequest.getPathInfo();
  Matcher matcher = ID_PATTERN.matcher(path);

  if (!matcher.matches()) {
    Responses.writeFailedResponse(baseRequest, response);
    return;
  }

  String id = matcher.group(1);

  response.setContentType(MediaType.JAVASCRIPT_UTF_8.toString());
  response.setStatus(HttpServletResponse.SC_OK);

  boolean hasValidCallbackParam = false;
  Writer responseWriter = response.getWriter();
  String callback = baseRequest.getParameter("callback");
  if (callback != null) {
    Matcher callbackMatcher = CALLBACK_PATTERN.matcher(callback);
    if (callbackMatcher.matches()) {
      hasValidCallbackParam = true;
      responseWriter.write(callback);
      responseWriter.write("(");
    }
  }

  responseWriter.write("[");

  Iterator<InputStream> traceStreams = buildTraces.getInputsForTraces(id).iterator();
  boolean isFirst = true;

  while (traceStreams.hasNext()) {
    if (!isFirst) {
      responseWriter.write(",");
    } else {
      isFirst = false;
    }
    try (InputStream input = traceStreams.next();
        InputStreamReader inputStreamReader = new InputStreamReader(input)) {
      CharStreams.copy(inputStreamReader, responseWriter);
    }
  }

  responseWriter.write("]");

  if (hasValidCallbackParam) {
    responseWriter.write(");\n");
  }

  response.flushBuffer();
  baseRequest.setHandled(true);
}
 
源代码19 项目: vjtools   文件: IOUtil.java
/**
 * 在Reader与Writer间复制内容
 * 
 * @see CharStreams#copy
 */
public static long copy(final Reader input, final Writer output) throws IOException {
	return CharStreams.copy(input, output);
}
 
源代码20 项目: vjtools   文件: IOUtil.java
/**
 * 在Reader与Writer间复制内容
 * 
 * @see {@link CharStreams#copy}
 */
public static long copy(final Reader input, final Writer output) throws IOException {
	return CharStreams.copy(input, output);
}