public static void writeFile(String fileName, String message){ try { CharSink charSink = Files.asCharSink(new File(fileName), Charsets.UTF_8, FileWriteMode.APPEND); charSink.write(message + "\n"); }catch(Exception e){ } }
private void extractOnlyOneTable(KeyspaceMetadata keyspace) throws Exception { File file = FileUtils.verify(filePath, force); if (!noddl) { System.out.println("Write \"" + tableName + "\" DDL to " + file.getCanonicalPath()); Files.asCharSink(file, Charset.defaultCharset(), FileWriteMode.APPEND) .write(TableExporter.genDDL(keyspace.getTable(tableName))); } if (!nodml) { TableExporter.genDML(this, keyspace.getTable(tableName), file); } }
@Test public void givenUsingGuava_whenWritingReaderContentsToFile_thenCorrect() throws IOException { Reader initialReader = new StringReader("Some text"); File targetFile = new File("src/test/resources/targetFile.txt"); com.google.common.io.Files.touch(targetFile); CharSink charSink = com.google.common.io.Files.asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND); charSink.writeFrom(initialReader); initialReader.close(); }
private static void trueMain(final String[] args) throws IOException { final Parameters input = Parameters.loadSerifStyle(new File(args[0])); final String resolved = input.dump(); final CharSink output = Files.asCharSink(new File(args[1]), Charsets.UTF_8, FileWriteMode.APPEND); output.write(resolved); }
protected void updateMessagesReportFile(final LogMessageOccurence log) { try { final File file = getLogMessagesReportFile(); file.getParentFile().mkdirs(); Files.asCharSink(file, StandardCharsets.UTF_8, FileWriteMode.APPEND).write(log.toString() + "\n"); } catch (IOException e) { LOG.error("Failed to append to file: {}", logMessagesReportFile.getPath(), e); } }
/** * For multiple operations, you will need to store your data * <p> * Could have used temp.deleteOnExit(); * </p> * <p> * Wont delete until jvm terminates. What if youre running in a webserver... * also has potential for memory leak * </p> */ @Test public void needToStoreBetweenOperations() throws IOException { ByteSource from = Res.byteSource(); File temp = File.createTempFile("partOne", ".xml"); try { duplicateInput(from, Files.asByteSink(temp, FileWriteMode.APPEND)); Processor.run(Files.asByteSource(temp), System.out); } finally { // dont expect this to run promptly (Effective Java - Item 7) temp.delete(); } }
@Test public void downloadProductImage() throws Exception { when(productImageSeeker.seekProductImage(anyLong())) .thenReturn(Resources.getResource("Large_Scaled_Forest_Lizard.jpg").openStream()); AtomicBoolean completed = new AtomicBoolean(false); AtomicBoolean error = new AtomicBoolean(false); File imageFile = File.createTempFile("image", ".jpg"); imageFile.deleteOnExit(); Files.touch(imageFile); ByteSink byteSink = Files.asByteSink(imageFile, FileWriteMode.APPEND); StreamObserver<DataChunk> streamObserver = new StreamObserver<DataChunk>() { @Override public void onNext(DataChunk dataChunk) { try { byteSink.write(dataChunk.getData().toByteArray()); } catch (IOException e) { log.error("error on write files", e); onError(e); } } @Override public void onError(Throwable t) { error.compareAndSet(false, true); } @Override public void onCompleted() { log.info("write image to {}", imageFile.getAbsoluteFile()); completed.compareAndSet(false, true); } }; stub.downloadProductImage(DownloadProductImageRequest.getDefaultInstance(), streamObserver); while (!completed.get() && !error.get()) { Thread.sleep(500); } assertThat(completed.get()).isTrue(); assertThat(error.get()).isFalse(); try (InputStream destImageStream = new FileInputStream(imageFile); InputStream origImageStream = Resources.getResource("Large_Scaled_Forest_Lizard.jpg").openStream()) { assertThat(DigestUtils.md5Hex(destImageStream)).isEqualTo( DigestUtils.md5Hex(origImageStream) ); } }
public void write(Object o, File file, FileWriteMode... modes) { write(o, Files.asByteSink(file, modes)); }
public static void writeFile(String fileName, String appendMsg, List<?> lists) throws IOException { CharSink charSink = Files.asCharSink(new File(fileName), Charsets.UTF_8, FileWriteMode.APPEND); charSink.write(appendMsg+ "\n"); charSink.write(lists.toString() +"\n"); }
public static void writeFile(String fileName, String appendMsg, Object object) throws IOException { CharSink charSink = Files.asCharSink(new File(fileName), Charsets.UTF_8, FileWriteMode.APPEND); charSink.write(appendMsg+"\n"); charSink.write(object.toString()+"\n"); }
static void genDML(SchemaExporter generator, TableMetadata table, File file) throws IOException, ExecutionException, InterruptedException { String tableName = Utils.escapeReservedWord(table.getName()); String keyspaceName = table.getKeyspace().getName(); CharSink charSink = Files.asCharSink(file, Charset.defaultCharset(), FileWriteMode.APPEND); System.out.printf("-----------------------------------------------" + Main.LINE_SEPARATOR); System.out.printf("Extract from %s.%s" + Main.LINE_SEPARATOR, keyspaceName, tableName); if (generator.truncate) { charSink.write(QueryBuilder.truncate(keyspaceName, tableName).getQueryString()); } Row firstRow = getFirstRow(generator.session, tableName, keyspaceName); if (firstRow == null) { return; } final List<String> colNames = new ArrayList(); final List<TypeCodec> typeCodecs = new ArrayList(); List<ColumnDefinitions.Definition> definitions = firstRow.getColumnDefinitions().asList(); for (ColumnDefinitions.Definition definition : definitions) { String colName = definition.getName(); DataType type = definition.getType(); colNames.add(Utils.escapeReservedWord(colName)); Object object = firstRow.getObject(colName); typeCodecs.add(object != null ? CODEC_REGISTRY.codecFor(type, object) : CODEC_REGISTRY .codecFor(type)); } String prefix = "INSERT INTO " + keyspaceName + "." + tableName + " (" + Joiner.on(',') .join(colNames) + ") VALUES ("; String postfix = generator.merge ? ") IF NOT EXISTS;" : ");"; long totalNoOfRows = getTotalNoOfRows(generator.session, tableName, keyspaceName); System.out.printf("Total number of record: %s" + Main.LINE_SEPARATOR, totalNoOfRows); int count = 0; Select select = QueryBuilder.select() .all() .from(keyspaceName, tableName).allowFiltering(); select.setFetchSize(SchemaExporter.FETCH_SIZE); ResultSet resultSet = generator.session.execute(select); Iterator<Row> iterator = resultSet.iterator(); System.out.printf("Start write \"%s\" data DML to %s" + Main.LINE_SEPARATOR, tableName, file.getCanonicalPath()); int noOfStep = getNoOfStep(totalNoOfRows); long step = totalNoOfRows / noOfStep; int stepCount = 0; while (iterator.hasNext()) { Row next = iterator.next(); String statement = generateInsertFromRow(typeCodecs, prefix, postfix, next) + Main.LINE_SEPARATOR; charSink.write(statement); count++; if (totalNoOfRows > SchemaExporter.FETCH_SIZE && count > stepCount * step) { float v = (float) count / (float) totalNoOfRows * 100; System.out.printf("Done %.2f%%" + Main.LINE_SEPARATOR, v); stepCount++; } } System.out.printf("Done exporting \"%s\", total number of records exported: %s" + Main.LINE_SEPARATOR, tableName, count); }