List of usage examples for java.io DataOutputStream write
public synchronized void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to the underlying output stream. From source file:com.webkey.Ipc.java
public void comBinAuth(String turl, String postData) { readAuthKey();/* w w w .j a v a 2 s . com*/ try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context); port = prefs.getString("port", "80"); Socket s = new Socket("127.0.0.1", Integer.parseInt(port)); //outgoing stream redirect to socket DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream()); byte[] utf = postData.getBytes("UTF-8"); dataOutputStream.writeBytes("POST /" + authKey + turl + " HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n"); dataOutputStream.write(utf, 0, utf.length); dataOutputStream.flush(); dataOutputStream.close(); s.close(); } catch (IOException e1) { //e1.printStackTrace(); } /* // Log.d(TAG,"post data"); String target = "http://127.0.0.1:"+port+"/"+authKey+turl; //Log.d(TAG,target); URL url = new URL(target); URLConnection conn = url.openConnection(); // Set connection parameters. conn.setDoInput (true); conn.setDoOutput (true); conn.setUseCaches (false); //Make server believe we are form data... conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream (conn.getOutputStream ()); // Write out the bytes of the content string to the stream. out.writeBytes(postData); out.flush (); out.close (); // Read response BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ())); String temp; String response = null; while ((temp = in.readLine()) != null){ response += temp + "\n"; } temp = null; in.close (); System.out.println("Server response:\n'" + response + "'"); }catch(Exception e){ Log.d(TAG,e.toString()); } */ }
From source file:com.webkey.Ipc.java
public void sendMessage(String message) { readAuthKey();//w ww . java 2s .c o m try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context); port = prefs.getString("port", "80"); Socket s = new Socket("127.0.0.1", Integer.parseInt(port)); //outgoing stream redirect to socket DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream()); byte[] utf = message.getBytes("UTF-8"); dataOutputStream.writeBytes("POST /" + authKey + "phonewritechatmessage HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n"); dataOutputStream.write(utf, 0, utf.length); dataOutputStream.flush(); dataOutputStream.close(); s.close(); } catch (IOException e1) { //e1.printStackTrace(); } }
From source file:org.apache.hadoop.raid.BlockFixer.java
/** * Reads data from the data stream provided and computes metadata. *//*from ww w.j a va2 s . co m*/ static DataInputStream computeMetadata(Configuration conf, InputStream dataStream) throws IOException { ByteArrayOutputStream mdOutBase = new ByteArrayOutputStream(1024 * 1024); DataOutputStream mdOut = new DataOutputStream(mdOutBase); // First, write out the version. mdOut.writeShort(FSDataset.METADATA_VERSION); // Create a summer and write out its header. int bytesPerChecksum = conf.getInt("io.bytes.per.checksum", 512); DataChecksum sum = DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_CRC32, bytesPerChecksum); sum.writeHeader(mdOut); // Buffer to read in a chunk of data. byte[] buf = new byte[bytesPerChecksum]; // Buffer to store the checksum bytes. byte[] chk = new byte[sum.getChecksumSize()]; // Read data till we reach the end of the input stream. int bytesSinceFlush = 0; while (true) { // Read some bytes. int bytesRead = dataStream.read(buf, bytesSinceFlush, bytesPerChecksum - bytesSinceFlush); if (bytesRead == -1) { if (bytesSinceFlush > 0) { boolean reset = true; sum.writeValue(chk, 0, reset); // This also resets the sum. // Write the checksum to the stream. mdOut.write(chk, 0, chk.length); bytesSinceFlush = 0; } break; } // Update the checksum. sum.update(buf, bytesSinceFlush, bytesRead); bytesSinceFlush += bytesRead; // Flush the checksum if necessary. if (bytesSinceFlush == bytesPerChecksum) { boolean reset = true; sum.writeValue(chk, 0, reset); // This also resets the sum. // Write the checksum to the stream. mdOut.write(chk, 0, chk.length); bytesSinceFlush = 0; } } byte[] mdBytes = mdOutBase.toByteArray(); return new DataInputStream(new ByteArrayInputStream(mdBytes)); }
From source file:org.apache.hadoop.tools.TestIntegrationByChunkThreads.java
private static void touchFile(String path, long totalFileSize, boolean preserveBlockSize, Options.ChecksumOpt checksumOpt) throws IOException { FileSystem fs;/*ww w. j a va 2 s .c o m*/ DataOutputStream outputStream = null; try { fs = cluster.getFileSystem(); final Path qualifiedPath = new Path(path).makeQualified(fs.getUri(), fs.getWorkingDirectory()); final long blockSize = preserveBlockSize ? NON_DEFAULT_BLOCK_SIZE : fs.getDefaultBlockSize(qualifiedPath) * 2; FsPermission permission = FsPermission.getFileDefault().applyUMask(FsPermission.getUMask(fs.getConf())); outputStream = fs.create(qualifiedPath, permission, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), 0, (short) (fs.getDefaultReplication(qualifiedPath) * 2), blockSize, null, checksumOpt); byte[] bytes = new byte[DEFAULT_BUFFER_SIZE]; long curFileSize = 0; int bufferLen = DEFAULT_BUFFER_SIZE; while (curFileSize < totalFileSize) { if (totalFileSize - curFileSize < DEFAULT_BUFFER_SIZE) bufferLen = (int) (totalFileSize - curFileSize); outputStream.write(bytes, 0, bufferLen); outputStream.flush(); curFileSize += bufferLen; } FileStatus fileStatus = fs.getFileStatus(qualifiedPath); System.out.println(fileStatus.getBlockSize()); System.out.println(fileStatus.getReplication()); } finally { IOUtils.cleanup(null, outputStream); } }
From source file:com.aliyun.openservices.odps.console.mapreduce.runtime.MapReduceJob.java
private boolean writeConfig(String fileName) throws OdpsException { try {/*ww w. ja va2 s. c o m*/ DataOutputStream out = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(new File(fileName)))); JSONObject result = new JSONObject(); if (!SetCommand.setMap.isEmpty()) { JSONObject obj = new JSONObject(SetCommand.setMap); result.put("settings", obj); } if (!SetCommand.aliasMap.isEmpty()) { JSONObject obj = new JSONObject(SetCommand.aliasMap); result.put("aliases", obj); } result.put("commandText", mrCmd.getCommandText()); result.put("context", context.toJson()); out.write(result.toString().getBytes(), 0, result.toString().getBytes().length); out.close(); } catch (IOException e) { throw new OdpsException("MapReduce write config error: " + e.getMessage()); } catch (JSONException je) { throw new OdpsException("MapReduce write config error: " + je.getMessage()); } return true; }
From source file:com.retroteam.studio.retrostudio.EditorLandscape.java
/** * Write the 8bit PCM audio to the wav file format to the public music dir. * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html * @param proj/*from www. ja v a2 s . c o m*/ * @param filename */ private void exportAsWav(Project proj, String filename) { try { File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), filename + ".wav"); DataOutputStream os = new DataOutputStream(new FileOutputStream(file)); // get project length int pLength = proj.export().getBytes().length; os.writeBytes("RIFF"); // Chunk ID 'RIFF' os.write(intToByteArray(36 + pLength), 0, 4); //file size os.writeBytes("WAVE"); // Wave ID os.writeBytes("fmt "); // Chunk ID 'fmt ' os.write(intToByteArray(16), 0, 4); // chunk size os.write(intToByteArray(1), 0, 2); // pcm audio os.write(intToByteArray(1), 0, 2); // mono os.write(intToByteArray(8000), 0, 4); // samples/sec os.write(intToByteArray(pLength), 0, 4); // bytes/sec os.write(intToByteArray(1), 0, 2); // 1 byte/sample os.write(intToByteArray(8), 0, 2); // 8 bits/sample os.writeBytes("data"); // Chunk ID 'data' os.write(intToByteArray(pLength), 0, 4); // size of data chunk os.write(proj.export().getBytes()); // write the data os.close(); Toast.makeText(this, "Saved file to: " + file.getPath(), Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(this, "IOException while saving project.", Toast.LENGTH_SHORT).show(); } }
From source file:UploadTest.java
@Test public void put_data_test() { String pid = "frl:6376979"; try {//from ww w. ja v a 2s. c om System.out.println(url); String charset = "UTF-8"; File file = new File("/home/raul/test/frl%3A6376984/6376986.pdf"); FileInputStream fi = new FileInputStream(file); httpCon.setDoOutput(true); httpCon.setDoInput(true); httpCon.setRequestMethod("PUT"); httpCon.setRequestProperty("Connection", "Keep-Alive"); httpCon.setRequestProperty("Content-Type", "application/pdf"); httpCon.setRequestProperty("type", "multipart/form-data"); httpCon.setRequestProperty("Accept", "application/data"); httpCon.setRequestProperty("uploaded_file", file.getPath()); System.out.println(file.getPath()); DataOutputStream out = new DataOutputStream(httpCon.getOutputStream()); System.out.println("130"); Files.copy(file.toPath(), out); int bytesRead; byte[] dataBuffer = new byte[1024]; while ((bytesRead = fi.read(dataBuffer)) != -1) { out.write(dataBuffer, 0, bytesRead); } System.out.println("137"); out.flush(); out.close(); System.out.println("140"); System.out.println("142"); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.sshd.server.sftp.SftpSubsystem.java
protected void send(Buffer buffer) throws IOException { DataOutputStream dos = new DataOutputStream(out); dos.writeInt(buffer.available());// w w w .ja v a 2s. c om dos.write(buffer.array(), buffer.rpos(), buffer.available()); dos.flush(); }
From source file:ict.servlet.UploadToServer.java
public static int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null; DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; }//from w w w . jav a 2s . c om try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); // close streams m_log.info("Upload file to server" + fileName + " File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { // ex.printStackTrace(); m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { // e.printStackTrace(); } //this block will give the response of upload link /* try { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { m_log.info("Huzza" + "RES Message: " + line); } rd.close(); } catch (IOException ioex) { m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex); }*/ return serverResponseCode; // like 200 (Ok) }
From source file:Main.java
public static String postMultiPart(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException { HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String[] q = filepath.split("/"); int idx = q.length - 1; try {// w ww.j a va2s . co m File file = new File(filepath); FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(urlTo); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); // Upload POST Data String[] posts = post.split("&"); int max = posts.length; for (int i = 0; i < max; i++) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); String[] kv = posts[i].split("="); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: text/plain" + lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(kv[1]); outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); inputStream = connection.getInputStream(); result = convertStreamToString(inputStream); fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { Log.e("MultipartRequest", "Multipart Form Upload Error"); e.printStackTrace(); return "error"; } }