下面列出了怎么用java.io.OutputStream的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void writeRandomAccessRead() throws IOException {
final Transaction txn = env.beginTransaction();
final File file0 = vfs.createFile(txn, "file0");
final OutputStream outputStream = vfs.appendFile(txn, file0);
outputStream.write((HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + HOEGAARDEN).getBytes(UTF_8));
outputStream.close();
txn.flush();
InputStream inputStream = vfs.readFile(txn, file0, 0);
Assert.assertEquals(HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream));
inputStream.close();
inputStream = vfs.readFile(txn, file0, 10);
Assert.assertEquals(HOEGAARDEN + HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream));
inputStream.close();
inputStream = vfs.readFile(txn, file0, 20);
Assert.assertEquals(HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream));
inputStream.close();
inputStream = vfs.readFile(txn, file0, 30);
Assert.assertEquals(HOEGAARDEN, streamAsString(inputStream));
inputStream.close();
txn.abort();
}
/**
* Creates a new COSOutputStream writes to an encoded COS stream.
*
* @param filters Filters to apply.
* @param parameters Filter parameters.
* @param output Encoded stream.
* @param scratchFile Scratch file to use.
*
* @throws IOException If there was an error creating a temporary buffer
*/
COSOutputStream(List<Filter> filters, COSDictionary parameters, OutputStream output,
ScratchFile scratchFile) throws IOException
{
super(output);
this.filters = filters;
this.parameters = parameters;
this.scratchFile = scratchFile;
if (filters.isEmpty())
{
this.buffer = null;
}
else
{
this.buffer = scratchFile.createBuffer();
}
}
/**
* 下载文件
*/
public static void downloadFile(HttpServletResponse response, String filePath) {
try {
String originalFileName = FilenameUtils.getName(filePath);
String downloadedFileName = new String(originalFileName.getBytes("GBK"), "ISO8859_1"); // 防止中文乱码
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=\"" + downloadedFileName + "\"");
InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
StreamUtil.copyStream(inputStream, outputStream);
} catch (Exception e) {
logger.error("下载文件出错!", e);
throw new RuntimeException(e);
}
}
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
is.close();
os.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
@Override
public void serializeBody(OutputStream stream) throws IOException {
StreamingUtils.writeInt(flags, stream);
StreamingUtils.writeTLString(id, stream);
StreamingUtils.writeTLString(type, stream);
if ((flags & FLAG_PHOTO) != 0) {
StreamingUtils.writeTLObject(photo, stream);
}
if ((flags & FLAG_DOCUMENT) != 0) {
StreamingUtils.writeTLObject(photo, stream);
}
if ((flags & FLAG_TITLE) != 0) {
StreamingUtils.writeTLString(title, stream);
}
if ((flags & FLAG_DESCRIPTION) != 0) {
StreamingUtils.writeTLString(title, stream);
}
StreamingUtils.writeTLObject(sendMessage, stream);
}
/**
* Implementation only supports unix line-end format and is suitable for
* processing HTTP and other network protocol communications. Reads and writes
* a line of data. Returns the number of bytes read/written.
*/
public static int readLine(InputStream in,
OutputStream out) throws IOException {
int count = 0;
for (;;) {
int b = in.read();
if (b == -1) {
break;
}
count++;
out.write(b);
if (b == '\n') {
break;
}
}
return count;
}
public void encode (@Nonnull @WillNotClose final InputStream aDecodedIS,
@Nonnull @WillNotClose final OutputStream aOS)
{
ValueEnforcer.notNull (aDecodedIS, "DecodedInputStream");
ValueEnforcer.notNull (aOS, "OutputStream");
try
{
int nByte;
while ((nByte = aDecodedIS.read ()) != -1)
{
aOS.write (StringHelper.getHexChar ((nByte & 0xf0) >> 4));
aOS.write (StringHelper.getHexChar (nByte & 0x0f));
}
}
catch (final IOException ex)
{
throw new EncodeException ("Failed to encode Base16", ex);
}
}
private void write(@NonNull OutputStream out, @NonNull BackupProtos.BackupFrame frame) throws IOException {
try {
Conversions.intToByteArray(iv, 0, counter++);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(cipherKey, "AES"), new IvParameterSpec(iv));
byte[] frameCiphertext = cipher.doFinal(frame.toByteArray());
byte[] frameMac = mac.doFinal(frameCiphertext);
byte[] length = Conversions.intToByteArray(frameCiphertext.length + 10);
out.write(length);
out.write(frameCiphertext);
out.write(frameMac, 0, 10);
} catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
throw new AssertionError(e);
}
}
protected WriterService createWriterService( final OutputStream out ) throws UnsupportedEncodingException {
final String encoding =
configuration.getConfigProperty( HtmlTableModule.ENCODING, EncodingRegistry.getPlatformDefaultEncoding() );
if ( isCreateBodyFragment() == false ) {
if ( isInlineStylesRequested() ) {
return WriterService.createPassThroughService( out, encoding );
} else {
if ( isExternalStyleSheetRequested() && isForceBufferedWriting() == false ) {
return WriterService.createPassThroughService( out, encoding );
} else {
return WriterService.createBufferedService( out, encoding );
}
}
} else {
return WriterService.createPassThroughService( out, encoding );
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
File dataDir = getDataDir();
fname = getName().replace("test", "");
File f = new File(dataDir, getClass().getName().
replaceAll("\\.", "/") + "/" + fname + ".fxml");
File w = new File(getWorkDir(), f.getName());
InputStream is = new FileInputStream(f);
OutputStream os = new FileOutputStream(w);
FileUtil.copy(is, os);
os.close();
is.close();
FileObject fo = FileUtil.toFileObject(w);
sourceDO = DataObject.find(fo);
document = ((EditorCookie)sourceDO.getCookie(EditorCookie.class)).openDocument();
hierarchy = TokenHierarchy.get(document);
}
static void help(JkCommandSet run, Path xmlFile) {
final Document document = JkUtilsXml.createDocument();
final Element runEl = RunClassDef.of(run).toElement(document);
document.appendChild(runEl);
if (xmlFile == null) {
JkUtilsXml.output(document, System.out);
} else {
JkUtilsPath.createFile(xmlFile);
try (final OutputStream os = Files.newOutputStream(xmlFile)) {
JkUtilsXml.output(document, os);
} catch (final IOException e) {
throw JkUtilsThrowable.unchecked(e);
}
JkLog.info("Xml help file generated at " + xmlFile);
}
}
@Override
public void serializeBody(OutputStream stream) throws IOException {
computeFlags();
writeInt(flags, stream);
writeTLObject(peer, stream);
writeInt(topMessage, stream);
writeInt(readInboxMaxId, stream);
writeInt(readOutboxMaxId, stream);
writeInt(unreadCount, stream);
writeTLObject(notifySettings, stream);
if ((flags & 1) != 0) {
if (pts == null) throwNullFieldException("pts", flags);
writeInt(pts, stream);
}
if ((flags & 2) != 0) {
if (draft == null) throwNullFieldException("draft", flags);
writeTLObject(draft, stream);
}
}
public static long copy(@WillNotClose InputStream in, @WillNotClose OutputStream out, long maxBytes)
throws IOException {
long total = 0;
int sz = 0;
byte buf[] = myByteBuf.get();
while (maxBytes > 0 && (sz = in.read(buf, 0, (int) Math.min(maxBytes, buf.length))) > 0) {
total += sz;
maxBytes -= sz;
out.write(buf, 0, sz);
}
return total;
}
@Override
public int serialize(OutputStream out, Tuple input) throws IOException {
JSONObject jsonObject = new JSONObject();
for (int i = 0; i < projectedPaths.length; i++) {
String [] paths = projectedPaths[i].split(NestedPathUtil.PATH_DELIMITER);
putValue(jsonObject, paths[0], paths, 0, i, input);
}
String jsonStr = jsonObject.toJSONString();
byte [] jsonBytes = jsonStr.getBytes(TextDatum.DEFAULT_CHARSET);
out.write(jsonBytes);
return jsonBytes.length;
}
/**
* Saves the mesh as OBJ format to the given {@link OutputStream}. Currently
* no texture coordinates are supported or written.
*
* @param stream
*/
public void saveAsOBJ(OutputStream stream) {
OBJWriter obj = new OBJWriter();
obj.beginSave(stream);
saveAsOBJ(obj);
obj.endSave();
}
public void getOutputStream(TGBrowserCallBack<OutputStream> cb, TGBrowserElement element) {
try {
throw new TGBrowserException("No writable file system");
} catch (Throwable e) {
cb.handleError(e);
}
}
public static void writeIntMM(OutputStream os, int value) throws IOException {
os.write(new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value});
}
public LinkHamp(InputStream is,
OutputStream os)
{
this(ServicesAmp.newManager().start(),
"remote://",
is, os);
}
/**
* Helper method trying to ensure that the file location provided by the user
* exists. If that is not the case it prompts the user if an empty
* configuration file should be created.
*
* @param location
* the configuration file location
* @throws CheckstylePluginException
* error when trying to ensure the location file existance
*/
private boolean ensureFileExists(String location) throws CheckstylePluginException {
// support dynamic location strings
String resolvedLocation = ExternalFileConfigurationType.resolveDynamicLocation(location);
File file = new File(resolvedLocation);
if (!file.exists()) {
boolean confirm = MessageDialog.openQuestion(mBtnBrowse.getShell(),
Messages.ExternalFileConfigurationEditor_titleFileDoesNotExist,
Messages.ExternalFileConfigurationEditor_msgFileDoesNotExist);
if (confirm) {
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
ConfigurationWriter.writeNewConfiguration(out, mWorkingCopy);
} catch (IOException ioe) {
CheckstylePluginException.rethrow(ioe);
}
return true;
}
return false;
}
return true;
}
static void writeLong(OutputStream os, long n) throws IOException {
os.write((byte)(n >>> 0));
os.write((byte)(n >>> 8));
os.write((byte)(n >>> 16));
os.write((byte)(n >>> 24));
os.write((byte)(n >>> 32));
os.write((byte)(n >>> 40));
os.write((byte)(n >>> 48));
os.write((byte)(n >>> 56));
}
/** {@inheritDoc} */
@Override protected void writeToSocket(
ClusterNode node,
Socket sock,
OutputStream out,
TcpDiscoveryAbstractMessage msg,
long timeout
) throws IOException, IgniteCheckedException {
if (isDrop(msg))
return;
super.writeToSocket(node, sock, out, msg, timeout);
}
private void writeRecordFields(final Record record, final RecordSchema schema, final OutputStream out) throws IOException {
final DataOutputStream dos = out instanceof DataOutputStream ? (DataOutputStream) out : new DataOutputStream(out);
for (final RecordField field : schema.getFields()) {
final Object value = record.getFieldValue(field);
try {
writeFieldRepetitionAndValue(field, value, dos);
} catch (final Exception e) {
throw new IOException("Failed to write field '" + field.getFieldName() + "'", e);
}
}
}
/**
* 書込みのテスト - メソッドにアノテーションを付与
*/
@Test
public void test_save_comment_method_anno() throws Exception {
// テストデータの作成
final MethodAnnoSheet outSheet = new MethodAnnoSheet();
outSheet.comment1("コメント1")
.comment2("コメント2");
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
mapper.save(template, out, outSheet);
}
// 書き込んだファイルを読み込み値の検証を行う。
try(InputStream in = new FileInputStream(outFile)) {
SheetBindingErrors<MethodAnnoSheet> errors = mapper.loadDetail(in, MethodAnnoSheet.class);
MethodAnnoSheet sheet = errors.getTarget();
assertThat(sheet.comment1Position).isEqualTo(CellPosition.of("B3"));
assertThat(sheet.comment2Position).isEqualTo(CellPosition.of("C5"));
assertThat(sheet.labels).isNull();
assertThat(sheet.comments).isNull();
assertThat(sheet.comment1).isEqualTo(outSheet.comment1);
assertThat(sheet.comment2).isEqualTo(outSheet.comment2);
}
}
private boolean copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
return true;
}
public void save(@NonNull MultiProfile profile) throws IOException, JSONException {
File file = new File(profilesPath, profile.id + ".profile");
try (OutputStream out = new FileOutputStream(file)) {
out.write(profile.toJson().toString().getBytes());
out.flush();
}
}
@Override
public void writeTo(DatasetConfig dataset, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
List<ViewFieldType> viewFieldTypes = ViewFieldsHelper.getViewFields(dataset);
ImmutableListMultimap<QlikFieldType, ViewFieldType> mapping = FluentIterable.from(viewFieldTypes).index(FIELD_TO_QLIKTYPE);
DatasetPath datasetPath = new DatasetPath(dataset.getFullPathList());
// qlik doesn't like certain characters as an identifier, so lets remove them
String sanitizedDatasetName = dataset.getName().replaceAll("["+ Pattern.quote("/[email protected] *-=+{}<>,~")+"]+", "_");
try (PrintWriter pw = new PrintWriter(entityStream)) {
pw.println("SET DirectIdentifierQuoteChar='" + QUOTE + "';");
pw.println();
pw.println("LIB CONNECT TO 'Dremio';");
pw.println();
// Create a resident load so that data can be referenced later
pw.format("%s: DIRECT QUERY\n", sanitizedDatasetName);
for(Map.Entry<QlikFieldType, Collection<ViewFieldType>> entry: mapping.asMap().entrySet()) {
writeFields(pw, entry.getKey().name(), entry.getValue());
}
/* Qlik supports paths with more than 2 components ("foo"."bar"."baz"."boo"), but each individual path segment
* must be quoted to work with Dremio. SqlUtils.quoteIdentifier will only quote when needed, so we do another
* pass to ensure they are quoted. */
final List<String> quotedPathComponents = Lists.newArrayList();
for (final String component : dataset.getFullPathList()) {
String quoted = SqlUtils.quoteIdentifier(component);
if (!quoted.startsWith(String.valueOf(SqlUtils.QUOTE)) || !quoted.endsWith(String.valueOf(SqlUtils.QUOTE))) {
quoted = quoteString(quoted);
}
quotedPathComponents.add(quoted);
}
pw.format(" FROM %1$s;\n", Joiner.on('.').join(quotedPathComponents));
}
}
/**
* engineStore currently is a No-op.
* Entries are stored to the token during engineSetEntry
*
* @param stream this must be <code>null</code>
* @param password this must be <code>null</code>
*/
public synchronized void engineStore(OutputStream stream, char[] password)
throws IOException, NoSuchAlgorithmException, CertificateException {
token.ensureValid();
if (stream != null && !token.config.getKeyStoreCompatibilityMode()) {
throw new IOException("output stream must be null");
}
if (password != null && !token.config.getKeyStoreCompatibilityMode()) {
throw new IOException("password must be null");
}
}
/**
* Unpack matching files from a jar. Entries inside the jar that do
* not match the given pattern will be skipped.
*
* @param jarFile the .jar file to unpack
* @param toDir the destination directory into which to unpack the jar
* @param unpackRegex the pattern to match jar entries against
*/
public static void unJar(File jarFile, File toDir, Pattern unpackRegex)
throws IOException {
JarFile jar = new JarFile(jarFile);
try {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (!entry.isDirectory() &&
unpackRegex.matcher(entry.getName()).matches()) {
InputStream in = jar.getInputStream(entry);
try {
File file = new File(toDir, entry.getName());
ensureDirectory(file.getParentFile());
OutputStream out = new FileOutputStream(file);
try {
IOUtils.copyBytes(in, out, 8192);
} finally {
out.close();
}
} finally {
in.close();
}
}
}
} finally {
jar.close();
}
}
void Write(OutputStream output) throws IOException {
BitUtils.WriteWord(output, localScreenWidth_);
BitUtils.WriteWord(output, localScreenHeight_);
output.write(byte_);
output.write(backgroundColorIndex_);
output.write(pixelAspectRatio_);
}
private void writeSignoff(OutputStream output, ImapSession session) {
try {
output.write(MAILBOX_DELETED_SIGNOFF);
} catch (IOException e) {
LOGGER.warn("Failed to write signoff");
LOGGER.debug("Failed to write signoff:", e);
}
}