Example usage for java.io DataOutputStream writeUTF

List of usage examples for java.io DataOutputStream writeUTF

Introduction

In this page you can find the example usage for java.io DataOutputStream writeUTF.

Prototype

public final void writeUTF(String str) throws IOException 

Source Link

Document

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

Usage

From source file:epn.edu.ec.bibliotecadigital.servidor.ServerRunnable.java

private void actualizarLibrosEnServidores(String fileName) {
    try {/*  www .  java  2s. co m*/
        Socket socket = new Socket("192.168.100.14", 8888);
        DataOutputStream dataOut = new DataOutputStream(socket.getOutputStream());
        dataOut.writeUTF("actualizar");
        dataOut.writeUTF("servidor");
        dataOut.writeUTF(fileName);
        OutputStream out = socket.getOutputStream();
        try {
            byte[] bytes = new byte[64 * 1024];
            InputStream in = new FileInputStream("C:\\Computacion Distribuida\\" + fileName);

            int count;
            while ((count = in.read(bytes)) > 0) {
                out.write(bytes, 0, count);
            }
            in.close();
        } finally {
            IOUtils.closeQuietly(out);
        }
    } catch (IOException ex) {
        Logger.getLogger(ServerRunnable.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.mutter.uninstallmonitor.MainApp.java

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    mInstance = getApplicationContext();
    new AsyncTask<Void, Void, String>() {

        @Override/*w  w w . ja  v  a2 s.c o  m*/
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
            try {
                DataOutputStream outputStream = new DataOutputStream(
                        openFileOutput(UNINSTALL_MONITOR, MODE_PRIVATE));
                outputStream.writeUTF("created for uninstall monitor");
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            String path = getFilesDir().getAbsolutePath() + File.separator + UNINSTALL_MONITOR;
            if (new File(path).exists()) {
                return path;
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result != null) {
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
                    forkUninstallMonitorProcess(result, getString(R.string.uninstall_intent_url));
                } else {
                    forkUninstallMonitorProcess(getApplicationInfo().dataDir,
                            getString(R.string.uninstall_intent_url));
                }
            }
        }

    }.execute(null, null, null);
}

From source file:com.facebook.infrastructure.db.Column.java

public void serialize(IColumn column, DataOutputStream dos) throws IOException {
    dos.writeUTF(column.name());
    dos.writeBoolean(column.isMarkedForDelete());
    dos.writeLong(column.timestamp());//from  ww w.j  av  a 2s  .  c o  m
    dos.writeInt(column.value().length);
    dos.write(column.value());
}

From source file:RetrieveAllMIDlet.java

public byte[] changeToByteArray() {
    byte[] data = null;

    try {//from w  w w  .  j ava  2 s .  com
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeUTF(name);
        dos.writeInt(chineseScore);
        dos.writeInt(englishScore);
        dos.writeInt(mathScore);
        data = baos.toByteArray();

        baos.close();
        dos.close();
    } catch (Exception e) {
    }
    return data;
}

From source file:com.bigdata.dastor.db.filter.QueryPath.java

public void serialize(DataOutputStream dos) throws IOException {
    assert !"".equals(columnFamilyName);
    assert superColumnName == null || superColumnName.length > 0;
    assert columnName == null || columnName.length > 0;
    dos.writeUTF(columnFamilyName == null ? "" : columnFamilyName);
    ColumnSerializer.writeName(superColumnName == null ? ArrayUtils.EMPTY_BYTE_ARRAY : superColumnName, dos);
    ColumnSerializer.writeName(columnName == null ? ArrayUtils.EMPTY_BYTE_ARRAY : columnName, dos);
}

From source file:com.csipsimple.backup.SipSharedPreferencesHelper.java

private void writeData(BackupDataOutput data, String value) throws IOException {
    // Create buffer stream and data output stream for our data
    ByteArrayOutputStream bufStream = new ByteArrayOutputStream();
    DataOutputStream outWriter = new DataOutputStream(bufStream);
    // Write structured data
    outWriter.writeUTF(value);
    // Send the data to the Backup Manager via the BackupDataOutput
    byte[] buffer = bufStream.toByteArray();
    int len = buffer.length;
    data.writeEntityHeader(SETTINGS_BACKUP_KEY, len);
    data.writeEntityData(buffer, len);//from  w  ww.j  ava 2 s .  com
}

From source file:org.apache.maven.plugin.eclipse.TempEclipseWorkspace.java

/**
 * Given the relative path from the workspace to the project to link use the basename as the project name and link
 * this project to the fully qualified path anchored at workspaceLocation.
 * /*from   w  w w. j  av  a 2  s .com*/
 * @param projectToLink The project to link
 * @throws MalformedURLException
 * @throws FileNotFoundException
 * @throws IOException
 */
private void writeLocationFile(String projectToLink) throws IOException {
    File projectToLinkAsRelativeFile = new File(projectToLink);

    File projectWorkspaceDirectory = new File(workspaceLocation, projectToLinkAsRelativeFile.getPath())
            .getCanonicalFile();
    String uriToProjectWorkspaceDirectory = "URI//" + projectWorkspaceDirectory.toURI().toURL().toString();

    File metaDataPlugins = new File(workspaceLocation,
            ReadWorkspaceLocations.METADATA_PLUGINS_ORG_ECLIPSE_CORE_RESOURCES_PROJECTS);
    File projectMetaDataDirectory = new File(metaDataPlugins, projectToLinkAsRelativeFile.getName());
    File locationFile = new File(projectMetaDataDirectory, ReadWorkspaceLocations.BINARY_LOCATION_FILE);

    DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(locationFile));

    dataOutputStream.write(ILocalStoreConstants.BEGIN_CHUNK);
    dataOutputStream.writeUTF(uriToProjectWorkspaceDirectory);
    dataOutputStream.write(ILocalStoreConstants.END_CHUNK);
    IOUtil.close(dataOutputStream);
}

From source file:MainClass.java

public void run() {
    try {//  w  ww .  ja v a  2  s  . co  m
        Socket client = serverSocket.accept();

        DataInputStream in = new DataInputStream(client.getInputStream());
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream out = new DataOutputStream(client.getOutputStream());

        while (true) {
            String message = in.readUTF();
            System.out.println(message);
            System.out.print("Enter response: ");
            String response = console.readLine();

            out.writeUTF(response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:J2MESearchMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  w  w w . j  a  v a  2s  .  co m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString[] = { "A", "B", "M" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();
            String inputString;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            if (recordstore.getNumRecords() > 0) {
                filter = new Filter("Mary");
                recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                while (recordEnumeration.hasNextElement()) {
                    recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                    inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt();
                    alert = new Alert("Reading", inputString, null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
            inputStream.close();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
                filter.filterClose();
                recordEnumeration.destroy();
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }
}

From source file:org.hyperic.hq.bizapp.agent.client.SecureAgentConnection.java

@Override
protected Socket getSocket() throws IOException {
    SSLSocket socket;//from  ww  w  . j  av a2s .  co  m

    log.debug("Creating secure socket");

    try {
        // Check for configured agent read timeout from System properties
        int readTimeout;

        try {
            readTimeout = Integer.parseInt(System.getProperty(PROP_READ_TIMEOUT));
        } catch (NumberFormatException e) {
            readTimeout = READ_TIMEOUT;
        }

        // Check for configured agent post handshake timeout
        // from System properties
        int postHandshakeTimeout;
        try {
            postHandshakeTimeout = Integer.parseInt(System.getProperty(PROP_POST_HANDSHAKE_TIMEOUT));
        } catch (NumberFormatException e) {
            postHandshakeTimeout = POST_HANDSHAKE_TIMEOUT;
        }

        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, acceptUnverifiedCertificate);

        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();

        // See the following links...
        // http://www.apache.org/dist/httpcomponents/httpcore/RELEASE_NOTES-4.1.x.txt
        // http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?message=13695343&cat=10&thread=73546&treeDisplayType=threadmode1&forum=178#13695343
        // In any case, it would seem as though the bug has since been fixed in IBM's JRE, no need to work around it anymore...
        socket = (SSLSocket) factory.createSocket();

        // Make sure the InetAddress used to initialize the socket has a non-null hostname (empty string).
        // This prevents slow and unnecessary reverse DNS querying when the connection is opened.
        InetAddress withoutHost = InetAddress.getByName(this.agentAddress);
        InetAddress withHost = InetAddress.getByAddress("", withoutHost.getAddress());
        InetSocketAddress address = new InetSocketAddress(withHost, this.agentPort);

        socket.connect(address, readTimeout);

        // Set the socket timeout during the initial handshake to detect
        // connection issues with the agent.  
        socket.setSoTimeout(readTimeout);

        log.debug("Secure socket is connected to " + address + " - starting handshake.");

        socket.startHandshake();

        log.debug("SSL handshake complete");

        // [HHQ-3694] The timeout is set to a post handshake value.
        socket.setSoTimeout(postHandshakeTimeout);

    } catch (IOException exc) {
        IOException toThrow = new IOException(
                "Unable to connect to " + this.agentAddress + ":" + this.agentPort + ": " + exc.getMessage());
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    // Write our security settings
    try {
        DataOutputStream dOs;

        dOs = new DataOutputStream(socket.getOutputStream());
        dOs.writeUTF(this.authToken);
    } catch (IOException exc) {
        IOException toThrow = new IOException("Unable to write auth params to server");
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    return socket;
}