下面列出了com.google.common.io.CharStreams#copy ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
}
}
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);
}
}
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);
}
}
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);
}
}
/**
* 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 ();
}
@Override
public void addPostInstallationScript ( final Reader reader ) throws IOException
{
try
{
CharStreams.copy ( reader, this.postInstallation );
}
finally
{
reader.close ();
}
}
@Override
public void addPreInstallationScript ( final Reader reader ) throws IOException
{
try
{
CharStreams.copy ( reader, this.preInstallation );
}
finally
{
reader.close ();
}
}
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();
}
@Override
public void addPreRemovalScript ( final Reader reader ) throws IOException
{
try
{
CharStreams.copy ( reader, this.preRemoval );
}
finally
{
reader.close ();
}
}
@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());
}
}
}
}
public static void copy(Reader input, Writer output) {
try {
CharStreams.copy(input, output);
output.flush();
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}
@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());
}
/**
* 将读取的内容拷贝到一个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());
}
/**
* 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;
}
}
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;
}
}
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();
}
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);
}
/**
* 在Reader与Writer间复制内容
*
* @see CharStreams#copy
*/
public static long copy(final Reader input, final Writer output) throws IOException {
return CharStreams.copy(input, output);
}
/**
* 在Reader与Writer间复制内容
*
* @see {@link CharStreams#copy}
*/
public static long copy(final Reader input, final Writer output) throws IOException {
return CharStreams.copy(input, output);
}