java.io.DataOutputStream.writeUTF()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(11.3k)|赞(0)|评价(0)|浏览(267)

本文整理了Java中java.io.DataOutputStream.writeUTF()方法的一些代码示例,展示了DataOutputStream.writeUTF()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。DataOutputStream.writeUTF()方法的具体详情如下:
包路径:java.io.DataOutputStream
类名称:DataOutputStream
方法名:writeUTF

DataOutputStream.writeUTF介绍

[英]Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.
[中]以独立于机器的方式使用modified UTF-8编码将字符串写入底层输出流。
首先,两个字节被写入输出流,就像通过writeShort方法写入一样,该方法给出了要跟随的字节数。该值是实际写入的字节数,而不是字符串的长度。在长度之后,字符串的每个字符都会使用修改后的UTF-8编码按顺序输出。如果未引发异常,则计数器written将按写入输出流的总字节数递增。这将至少是两个加上长度str,最多是两个加上长度str的三倍。

代码示例

代码示例来源:origin: stanfordnlp/CoreNLP

protected void save(DataOutputStream f) throws IOException {
 f.writeInt(num);
 f.writeUTF(val);
 f.writeUTF(tag);
}

代码示例来源:origin: jenkinsci/jenkins

protected final void send(Op op, String text) throws IOException {
  ByteArrayOutputStream buf = new ByteArrayOutputStream();
  new DataOutputStream(buf).writeUTF(text);
  send(op, buf.toByteArray());
}

代码示例来源:origin: log4j/log4j

static
 void roll() {
  try {
   Socket socket = new Socket(host, port);
   DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
   DataInputStream dis = new DataInputStream(socket.getInputStream());
   dos.writeUTF(ExternallyRolledFileAppender.ROLL_OVER);
   String rc = dis.readUTF();
   if(ExternallyRolledFileAppender.OK.equals(rc)) {
  cat.info("Roll over signal acknowledged by remote appender.");
   } else {
  cat.warn("Unexpected return code "+rc+" from remote entity.");
  System.exit(2);
   }
  } catch(IOException e) {
   cat.error("Could not send roll signal on host "+host+" port "+port+" .",
    e);
   System.exit(2);
  }
  System.exit(0);
 }
}

代码示例来源:origin: jenkinsci/jenkins

ByteArrayOutputStream rsp = new ByteArrayOutputStream();
while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) {
  int ch = s.getInputStream().read();
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Protocol:CLI-connect");
DataInputStream dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Protocol:CLI2-connect");
String greeting = dis.readUTF();
if (!greeting.equals("Welcome"))

代码示例来源:origin: deeplearning4j/nd4j

/**
 * Write the data header
 *
 * @param stream the output stream
 * @param header the header to write
 * @throws IOException
 */
private void writeHeader(OutputStream stream, Header header) throws IOException {
  DataOutputStream dos = new DataOutputStream(stream);
  dos.writeUTF(HEADER);
  // Write the current version
  dos.writeInt(1);
  // Write the normalizer opType
  dos.writeUTF(header.normalizerType.toString());
  // If the header contains a custom class opName, write that too
  if (header.customStrategyClass != null) {
    dos.writeUTF(header.customStrategyClass.getName());
  }
}

代码示例来源:origin: stackoverflow.com

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

代码示例来源:origin: btraceio/btrace

private static void writeLdc(LdcInsnNode lin, DataOutputStream dos) throws IOException {
  Object o = lin.cst;
  if (o instanceof Integer) {
    dos.writeShort(1);
    dos.writeInt((Integer)o);
  } else if (o instanceof Float) {
    dos.writeShort(2);
    dos.writeFloat((Float)o);
  } else if (o instanceof Long) {
    dos.writeShort(3);
    dos.writeLong((Long)o);
  } else if (o instanceof Double) {
    dos.writeShort(4);
    dos.writeDouble((Double)o);
  } else if (o instanceof String) {
    dos.writeShort(5);
    dos.writeUTF((String)o);
  } else if (o instanceof Type) {
    dos.writeShort(6);
    dos.writeUTF(((Type)o).getDescriptor());
  } else {
    dos.writeShort(0);
  }
}

代码示例来源:origin: jenkinsci/jenkins

public boolean connect(Socket socket) throws IOException {
    try {
      LOGGER.log(Level.FINE, "Requesting ping from {0}", socket.getRemoteSocketAddress());
      try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
        out.writeUTF("Protocol:Ping");
        try (InputStream in = socket.getInputStream()) {
          byte[] response = new byte[ping.length];
          int responseLength = in.read(response);
          if (responseLength == ping.length && Arrays.equals(response, ping)) {
            LOGGER.log(Level.FINE, "Received ping response from {0}", socket.getRemoteSocketAddress());
            return true;
          } else {
            LOGGER.log(Level.FINE, "Expected ping response from {0} of {1} got {2}", new Object[]{
                socket.getRemoteSocketAddress(),
                new String(ping, "UTF-8"),
                responseLength > 0 && responseLength <= response.length ?
                  new String(response, 0, responseLength, "UTF-8") :
                  "bad response length " + responseLength
            });
            return false;
          }
        }
      }
    } finally {
      socket.close();
    }
  }
}

代码示例来源:origin: apache/geode

public GFSnapshotExporter(File out, String region, InternalCache cache) throws IOException {
 this.cache = cache;
 FileOutputStream fos = new FileOutputStream(out);
 fc = fos.getChannel();
 dos = new DataOutputStream(new BufferedOutputStream(fos));
 // write snapshot version
 dos.writeByte(SNAP_VER_2);
 // write format type
 dos.write(SNAP_FMT);
 // write temporary pdx location in bytes 4-11
 dos.writeLong(-1);
 // write region name
 dos.writeUTF(region);
}

代码示例来源:origin: apache/nifi

public static void rejectCodecNegotiation(final DataInputStream dis, final DataOutputStream dos, final String explanation) throws IOException {
  dis.readUTF();  // read codec name
  dis.readInt();  // read codec version
  dos.write(ABORT);
  dos.writeUTF(explanation);
  dos.flush();
}

代码示例来源:origin: robovm/robovm

output.writeUTF(classDesc.getName());
output.writeLong(classDesc.getSerialVersionUID());
byte flags = classDesc.getFlags();

代码示例来源:origin: google/ExoPlayer

/** Serializes {@code action} type and data into the {@code output}. */
public static void serializeToStream(DownloadAction action, OutputStream output)
  throws IOException {
 // Don't close the stream as it closes the underlying stream too.
 DataOutputStream dataOutputStream = new DataOutputStream(output);
 dataOutputStream.writeUTF(action.type);
 dataOutputStream.writeInt(action.version);
 action.writeToStream(dataOutputStream);
 dataOutputStream.flush();
}

代码示例来源:origin: hankcs/HanLP

static boolean saveDat(String path, TreeMap<String, String> map)
{
  Collection<String> dependencyList = map.values();
  // 缓存值文件
  try
  {
    DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(path +  ".bi" + Predefine.BIN_EXT));
    out.writeInt(dependencyList.size());
    for (String dependency : dependencyList)
    {
      out.writeUTF(dependency);
    }
    if (!trie.save(out)) return false;
    out.close();
  }
  catch (Exception e)
  {
    logger.warning("保存失败" + e);
    return false;
  }
  return true;
}

代码示例来源:origin: apache/kylin

public static void serialize(Dictionary<?> dict, OutputStream outputStream) {
  try {
    DataOutputStream out = new DataOutputStream(outputStream);
    out.writeUTF(dict.getClass().getName());
    dict.write(out);
    out.flush();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: HotswapProjects/HotswapAgent

public void write(DataOutputStream out) throws IOException {
    if (value instanceof String) {
      out.writeByte(CONSTANT_UTF8);
      out.writeUTF((String) value);
    } else if (value instanceof Integer) {
      out.writeByte(CONSTANT_INTEGER);
      out.writeInt(((Integer) value).intValue());
    } else if (value instanceof Float) {
      out.writeByte(CONSTANT_FLOAT);
      out.writeFloat(((Float) value).floatValue());
    } else if (value instanceof Long) {
      out.writeByte(CONSTANT_LONG);
      out.writeLong(((Long) value).longValue());
    } else if (value instanceof Double) {
      out.writeDouble(CONSTANT_DOUBLE);
      out.writeDouble(((Double) value).doubleValue());
    } else {
      throw new InternalError("bogus value entry: " + value);
    }
  }
}

代码示例来源:origin: apache/kylin

private void readWriteTest(Dictionary<String> dict) throws Exception {
    final String path = "src/test/resources/dict/tmp_dict";
    File f = new File(path);
    f.deleteOnExit();
    f.createNewFile();
    String dictClassName = dict.getClass().getName();
    DataOutputStream out = new DataOutputStream(new FileOutputStream(f));
    out.writeUTF(dictClassName);
    dict.write(out);
    out.close();
    //read dict
    DataInputStream in = null;
    Dictionary<String> dict2 = null;
    try {
      File f2 = new File(path);
      in = new DataInputStream(new FileInputStream(f2));
      String dictClassName2 = in.readUTF();
      dict2 = (Dictionary<String>) ClassUtil.newInstance(dictClassName2);
      dict2.readFields(in);
    } finally {
      if (in != null) {
        in.close();
      }
    }
    assertTrue(dict.equals(dict2));
  }
}

代码示例来源:origin: google/ExoPlayer

@Override
protected void writeToStream(DataOutputStream output) throws IOException {
 output.writeUTF(uri.toString());
 output.writeBoolean(isRemoveAction);
 output.writeInt(data.length);
 output.write(data);
 boolean customCacheKeySet = customCacheKey != null;
 output.writeBoolean(customCacheKeySet);
 if (customCacheKeySet) {
  output.writeUTF(customCacheKey);
 }
}

代码示例来源:origin: jenkinsci/jenkins

@Override
  public void run() throws IOException, InterruptedException {
    try {
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());
      out.writeUTF("Welcome");
      // perform coin-toss and come up with a session key to encrypt data
      Connection c = new Connection(socket);
      byte[] secret = c.diffieHellman(true).generateSecret();
      SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret,128/8),"AES");
      c = c.encryptConnection(sessionKey,"AES/CFB8/NoPadding");
      try {
        // HACK: TODO: move the transport support into modules
        Class<?> cls = Jenkins.getActiveInstance().pluginManager.uberClassLoader.loadClass("org.jenkinsci.main.modules.instance_identity.InstanceIdentity");
        Object iid = cls.getDeclaredMethod("get").invoke(null);
        PrivateKey instanceId = (PrivateKey)cls.getDeclaredMethod("getPrivate").invoke(iid);
        // send a signature to prove our identity
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(instanceId);
        signer.update(secret);
        c.writeByteArray(signer.sign());
      } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new Error(e);
      }
      runCli(c);
    } catch (GeneralSecurityException e) {
      throw new IOException("Failed to encrypt the CLI channel",e);
    }
  }
}

代码示例来源:origin: apache/nifi

public void writeResponse(final DataOutputStream out, final String explanation) throws IOException {
  if (!containsMessage()) {
    throw new IllegalArgumentException("ResponseCode " + code + " does not expect an explanation");
  }
  out.write(getCodeSequence());
  out.writeUTF(explanation);
  out.flush();
}

代码示例来源:origin: org.easymock/easymock

private static byte[] getSerializedBytes(Class<?> clazz) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try (DataOutputStream data = new DataOutputStream(baos)) {
    data.writeShort(ObjectStreamConstants.STREAM_MAGIC);
    data.writeShort(ObjectStreamConstants.STREAM_VERSION);
    data.writeByte(ObjectStreamConstants.TC_OBJECT);
    data.writeByte(ObjectStreamConstants.TC_CLASSDESC);
    data.writeUTF(clazz.getName());
    Long suid = getSerializableUID(clazz);
    data.writeLong(suid);
    data.writeByte(2); // classDescFlags (2 = Serializable)
    data.writeShort(0); // field count
    data.writeByte(ObjectStreamConstants.TC_ENDBLOCKDATA);
    data.writeByte(ObjectStreamConstants.TC_NULL);
  }
  return baos.toByteArray();
}

相关文章