Exemplo n.º 1
0
  public void writeBinaryStream(String bytes) {
    try {
      if (dos != null) {
        for (int i = 0; i < 1; i++) {
          // write boolean value.
          dos.writeBoolean(true);

          // "C1 01 00 00 14 00 00 0D 00 00 FF 05
          // 00010102021101010102030904020A0000090600000A0064FF120001"
          // dos.write(b);
          // dos.writeChars("\n");
          //
          //	dos.writeChars("C10100001400000D0000FF0500010102021101010102030904020A0000090600000A0064FF120001");
          //					dos.writeChars("\n");
          //
          //	dos.writeChars("C10100001400000D0000FF08000101020809067765656B30301104110511021101110211041101");
          //					dos.writeChars("\n");
          //
          //	dos.writeChars("C10100001400000D0000FF070001010203090673656173306E090C07DC0B0001FFFFFF0080000009077765656B303020");
          //					dos.writeChars("\n");
          //					dos.writeChars("C10100000B00000B0000FF0200010102031200010905056F0615031101");

          dos.writeChars(bytes);
        }
        dos.flush();
        dos.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 2
0
 /**
  * Write the symbol table to a data output stream. This method is designed to write a symbol table
  * as part of an output stream, so the stream is not closed after the symbol table is written. The
  * bytes may be read in through a data input stream using the static {@link
  * #read(DataInputStream)}. The format is described in {@link #read(DataInputStream)}.
  *
  * @param out Data output stream to which the symbol table is written.
  * @throws IOException If there is an exception writing to the underlying stream.
  */
 public void write(DataOutputStream out) throws IOException {
   out.writeInt(numSymbols());
   for (int i = 0; i < numSymbols(); ++i) {
     String symbol = idToSymbol(i);
     out.writeShort(symbol.length());
     out.writeChars(symbol);
   }
 }
Exemplo n.º 3
0
 public static void writeString(String par0Str, DataOutputStream par1DataOutputStream)
     throws IOException {
   if (par0Str.length() > 32767) {
     throw new IOException("String too big");
   } else {
     par1DataOutputStream.writeShort(par0Str.length());
     par1DataOutputStream.writeChars(par0Str);
   }
 }
  public static void main(String[] args) {

    try {
      String filename = "fileToLock.dat";
      File file = new File(filename);
      file.createNewFile();

      // Creates a random access file stream to read from, and optionally
      // to write to
      FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

      DataOutputStream out2 =
          new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
      out2.writeDouble(3.14159);
      out2.writeChars("That was pi\n");
      out2.writeBytes("That was pi\n");
      out2.close();

      // Acquire an exclusive lock on this channel's file ( block until
      // the region can be
      // locked, this channel is closed, or the invoking thread is
      // interrupted)
      FileLock lock = channel.lock(0, Long.MAX_VALUE, false);

      System.out.print("Press any key...");
      System.in.read();
      // Attempts to acquire an exclusive lock on this channel's file
      // (does not block, an
      // invocation always returns immediately, either having acquired a
      // lock on the requested
      // region or having failed to do so.
      try {

        lock = channel.tryLock(0, Long.MAX_VALUE, true);
      } catch (OverlappingFileLockException e) {
        // thrown when an attempt is made to acquire a lock on a a file
        // that overlaps
        // a region already locked by the same JVM or when another
        // thread is already
        // waiting to lock an overlapping region of the same file
        System.out.println("Overlapping File Lock Error: " + e.getMessage());
      }

      // tells whether this lock is shared
      boolean isShared = lock.isShared();

      // release the lock
      lock.release();

      // close the channel
      channel.close();

    } catch (IOException e) {
      System.out.println("I/O Error: " + e.getMessage());
    }
  }
Exemplo n.º 5
0
 public static void main(String[] params) {
   try {
     socket = new Socket("localhost", puerto);
     dos = new DataOutputStream(socket.getOutputStream());
     DataInputStream dis = new DataInputStream(socket.getInputStream());
     dos.writeChars("Hola mundo");
     dos.close();
     socket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 6
0
 private void dump_console() {
   try {
     DataOutputStream file =
         new DataOutputStream(
             new BufferedOutputStream(new FileOutputStream(file_location("_console.bin"))));
     file.writeChars(mLV.getText().toString());
     file.close();
   } catch (FileNotFoundException e) {
     mLV.addtext("Could open file for dumping");
   } catch (IOException e1) {
     mLV.addtext("Could not dump the console");
   }
 }
Exemplo n.º 7
0
  public void writeData(String path, String info) {

    // 使用 FileOutputStream
    try (OutputStream fileOutputStream = new FileOutputStream(path /* , boolean append*/)) {
      byte[] infoByte = info.getBytes();
      fileOutputStream.write(infoByte);
      fileOutputStream.write('\n');
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 使用 BufferedOutputStream 嵌套,更利于网络不稳定的环境下的输出.
    try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(path, true))) {
      byte[] infoByte = info.getBytes();
      outputStream.write(infoByte);
      outputStream.write('\n');
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 使用 DataOutputStream 输出数字数据.是以二进制格式输出,所以也只能以二进制方式读DataInputStream.
    // 由于其根据数据类型输出固定位的字节,int 4位,double 8位,所以解析速度更快.
    try (DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(path, true))) {
      byte[] infoByte = info.getBytes();
      outputStream.writeInt(3); // 该方法的写数据方法并不能在文件中看到正确显示,他有自己的写入规则,
      outputStream.writeDouble(3.111); // 用read方法读的时候可以看到正确的形式
      outputStream.write(infoByte);
      outputStream.writeUTF(info); // 该方法写入的UTF数据会在头部加2byte数据,用readUTF方法可以正确显示.
      // 除非是用于Java虚拟机的字符串,否则都应该用 writeChars()
      outputStream.writeChars(info);
      outputStream.write('\n');
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 使用 FileWriter, OutputStreamWriter 同理.继承关系是 Writer -> OutputStreamWriter -> FileWriter
    try (FileWriter fileWriter = new FileWriter(path, true)) {
      char[] infoByte = info.toCharArray();
      fileWriter.write(infoByte); // 注意 Writer 一类的流不能写 byte
      fileWriter.write("4" + info + "encoding=" + fileWriter.getEncoding() + "\n");
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 使用 PrintWriter,不使用 PrintStream,之所以还保留这个方法是为了兼容 System.out 这个.
    try (PrintWriter printWriter =
        new PrintWriter(new FileOutputStream(path, true)) /*, boolean append*/) {
      // 如果需要在文件后追加就必须使用上述构造方法,没有 PrintWriter(String filename, boolean append) 方法.
      printWriter.println(info);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @Override
  protected void javaToNative(Object data, TransferData transferData) {
    if (!(data instanceof ArtifactData)) {
      return;
    }

    ArtifactData artData = (ArtifactData) data;
    /**
     * The resource serialization format is: (int) number of artifacts Then, the following for each
     * resource: (int) artID (int) tagID Then the following (int) urlLength (int) sourceLength
     * (chars) url (chars) source
     */
    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      DataOutputStream dataOut = new DataOutputStream(out);

      // write the number of resources
      dataOut.writeInt(artData.getArtifacts().length);

      for (Artifact artifact : artData.getArtifacts()) {
        writeArtifact(dataOut, artifact);
      }
      dataOut.writeInt(artData.getUrl().length());
      dataOut.writeInt(artData.getSource().length());
      dataOut.writeChars(artData.getUrl());
      dataOut.writeChars(artData.getSource());

      // cleanup
      dataOut.close();
      out.close();
      byte[] bytes = out.toByteArray();
      super.javaToNative(bytes, transferData);
    } catch (Exception e) {
      // it's best to send nothing if there were problems
    }
  }
Exemplo n.º 9
0
  public static void saveRecord(InputStream input, FileOutputStream output, Record record) {

    DataOutputStream out = new DataOutputStream(output);

    List<Record> records = new ArrayList<Record>();
    try {

      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(input);
      doc.getDocumentElement().normalize();

      NodeList nList = doc.getDocumentElement().getChildNodes();

      for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element element = (Element) nNode;

          String jogador = element.getAttribute("jogador");
          int clicks = Integer.parseInt(element.getAttribute("clicks"));
          long tempo = Long.parseLong(element.getAttribute("tempo"));

          records.add(new Record(jogador, clicks, tempo));
        }
      }
      records.add(record);
      Collections.sort(records);

      Log.i(Contants.TAG, records.toString());

      out.writeChars(
          "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Game><Record jogador=\"A\" clicks=\"1\" tempo=\"1000\" /></Game>");
      out.flush();

    } catch (Exception e) {
      Log.e(Contants.TAG, e.getMessage());
    }
  }
Exemplo n.º 10
0
  public void startApp() {

    try {
      byte[] input = {
        -2, 54, -2, -2, 1, 0, -128, 1, 91, -64, 0x0C, 0x7A, -31, 0x47, -82, 0x14, 0x7B, 0x41, 0x09,
        0x1d, 0x25, 122, 121, 0, 120, -1, -7, 0x51, 0x54, -1, -1, -1, -1, -1, -7, 0x51, 0x54, -14,
        0x16, 0, 10, -59, -101, 99, 105, -61, -77, -59, -126, 107, 97
      };
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      DataOutputStream s = new DataOutputStream(out);
      s.write(254);
      byte[] bb = {54, -2};
      s.write(bb);
      s.write(bb, 1, 1);
      s.writeBoolean(true);
      s.writeBoolean(false);
      s.writeByte(-128);
      s.writeChar('ś');
      s.writeDouble(-3.56);
      s.writeFloat(8.569615f);
      s.writeChars("穹x");
      s.writeInt(-437932);
      s.writeLong(-437932l);
      s.writeShort(-3562);
      s.writeUTF("ściółka");
      s.flush();
      bb = out.toByteArray();
      compare(bb.length, input.length);
      for (int i = 0; i < bb.length; i++) {
        compare(bb[i], input[i]);
      }
      s.close();

    } catch (Exception e) {
      e.printStackTrace();
      check(false);
    }
    finish();
  }
Exemplo n.º 11
0
  public static void main(String[] args) {
    File db = new File(DB_FILE);
    FileOutputStream fs;

    try {
      fs = new FileOutputStream(db, true);

      DataOutputStream dos = new DataOutputStream(fs);

      IEmployee employee1 =
          new Employee("Carol", "Lindsey", 43, "ofice-assistant", new BigDecimal(1760));
      IEmployee employee2 = new Employee("Gorden", "Brown", 56, "cleaner", new BigDecimal(1230));
      IEmployee employee3 = new Employee("Brian", "Lindsey", 47, "CSO", new BigDecimal(5760));

      try {
        dos.writeChars(employee1.toString());
        dos.writeChars("\n");

        dos.writeChars(employee2.toString());
        dos.writeChars("\n");

        dos.writeChars(employee3.toString());
        dos.writeChars("\n");

        dos.close();
      } catch (IOException e) {
        out.printf("Cannot write to file (%s). %s", DB_FILE, e.toString());
      }

      fs.close();
    } catch (FileNotFoundException e) {
      out.printf("File not found (%s). %s", DB_FILE, e.toString());
      //         e.printStackTrace();  //To change body of catch statement use File | Settings |
      // File Templates.
    } catch (IOException e) {
      out.printf("Couldn't close file (%s). %s", DB_FILE, e.toString());
      //         e.printStackTrace();  //To change body of catch statement use File | Settings |
      // File Templates.
    }
  }
 public final void writeChars(String s) throws IOException {
   dos_.writeChars(s);
 }
Exemplo n.º 13
0
 /**
  * Dump the players genome out to a data file (which can be read later in the case of restart or
  * to analyze the player).
  */
 @Override
 public void dumpGenome(DataOutputStream out) throws IOException {
   out.writeChars("RGA");
   super.dumpGenome(out);
 }
Exemplo n.º 14
0
  public void testSetLabel() throws Exception {
    LocalHistoryTestStore store = createStore();
    LogHandler lh = new LogHandler("copied file", LogHandler.Compare.STARTS_WITH);

    File folder = new File(dataDir, "datafolder");
    folder.mkdirs();

    // create the file
    File file1 = new File(folder, "file1");

    // lets create some history
    long ts = System.currentTimeMillis() - 4 * 24 * 60 * 60 * 1000;
    createFile(store, file1, ts + 1000, "data1");
    lh.reset();
    changeFile(store, file1, ts + 2000, "data1.1");
    lh.waitUntilDone();
    lh.reset();
    changeFile(store, file1, ts + 3000, "data1.2");
    lh.waitUntilDone();

    assertFile(file1, store, ts + 3000, -1, 3, 1, "data1.2", TOUCHED);

    String label = "My most beloved label";
    store.setLabel(file1, ts + 2000, label);

    assertFile(file1, store, ts + 3000, -1, 3, 1, "data1.2", TOUCHED, true);

    File labelsFile = store.getLabelsFile(file1);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.writeLong(ts + 2000);
    dos.writeInt(label.length());
    dos.writeChars(label);
    dos.flush();

    assertDataInFile(labelsFile, baos.toByteArray());

    label = "My second most beloved label";
    store.setLabel(file1, ts + 1000, label);

    dos.writeLong(ts + 1000);
    dos.writeInt(label.length());
    dos.writeChars(label);
    dos.flush();

    labelsFile = store.getLabelsFile(file1);
    assertDataInFile(labelsFile, baos.toByteArray());

    store.setLabel(file1, ts + 2000, null);

    baos = new ByteArrayOutputStream();
    dos = new DataOutputStream(baos);
    dos.writeLong(ts + 1000);
    dos.writeInt(label.length());
    dos.writeChars(label);
    dos.flush();

    labelsFile = store.getLabelsFile(file1);
    assertDataInFile(labelsFile, baos.toByteArray());

    dos.close();
  }
Exemplo n.º 15
0
  public static void main(String[] args) {
    String filename = "data-out.dat";
    String message = "Hi,您好!";

    // Write primitives to an output file
    try {
      DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
      //            DataOutputStream out =
      //                    new DataOutputStream(
      //                    new BufferedOutputStream(
      //                    new FileOutputStream(filename)));
      out.writeByte(127);
      out.writeShort(0xFFFF); // -1
      out.writeInt(0xABCD);
      out.writeLong(0x1234); // JDK 7 syntax
      out.writeFloat(11.22f);
      out.writeDouble(55.66);
      out.writeBoolean(true);
      out.writeBoolean(false);
      for (int i = 0; i < message.length(); i++) {
        out.writeChar(message.charAt(i));
      }
      out.writeChars(message);
      out.writeBytes(message);
      out.flush();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Read raw bytes and print in Hex
    try {
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
      int inByte;
      while ((inByte = in.read()) != -1) {
        System.out.printf("%02X ", inByte); // Print Hex codes
      }
      System.out.printf("%n%n");
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Read primitives
    try {
      DataInputStream in = new DataInputStream(new FileInputStream(filename));
      System.out.println("byte:    " + in.readByte());
      System.out.println("short:   " + in.readShort());
      System.out.println("int:     " + in.readInt());
      System.out.println("long:    " + in.readLong());
      System.out.println("float:   " + in.readFloat());
      System.out.println("double:  " + in.readDouble());
      System.out.println("boolean: " + in.readBoolean());
      System.out.println("boolean: " + in.readBoolean());

      System.out.print("char:    ");
      for (int i = 0; i < message.length(); i++) {
        System.out.print(in.readChar());
      }
      System.out.println();

      System.out.print("chars:   ");
      for (int i = 0; i < message.length(); i++) {
        System.out.print(in.readChar());
      }
      System.out.println();

      System.out.print("bytes:   ");
      for (int i = 0; i < message.length(); i++) {
        System.out.print((char) in.readByte());
      }
      System.out.println();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
Exemplo n.º 16
0
 @Override
 public void writeChars(String s) throws IOException {
   dos.writeChars(s);
 }