/** * Starts a native process on the server * * @param command the command to start the process * @param dir the dir in which the process starts */ static String startProcess(String command, String dir) throws IOException { StringBuffer ret = new StringBuffer(); String[] comm = new String[3]; comm[0] = COMMAND_INTERPRETER[0]; comm[1] = COMMAND_INTERPRETER[1]; comm[2] = command; long start = System.currentTimeMillis(); try { // Start process Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir)); // Get input and error streams BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream()); BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream()); boolean end = false; while (!end) { int c = 0; while ((ls_err.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_err.read())); } c = 0; while ((ls_in.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_in.read())); } try { ls_proc.exitValue(); // if the process has not finished, an exception is thrown // else while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read())); while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read())); end = true; } catch (IllegalThreadStateException ex) { // Process is running } // The process is not allowed to run longer than given time. if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) { ls_proc.destroy(); end = true; ret.append("!!!! Process has timed out, destroyed !!!!!"); } try { Thread.sleep(50); } catch (InterruptedException ie) { } } } catch (IOException e) { ret.append("Error: " + e); } return ret.toString(); }
static void initWords(int size, Object[] key, Object[] abs) { String fileName = "testwords.txt"; int ki = 0; int ai = 0; try { FileInputStream fr = new FileInputStream(fileName); BufferedInputStream in = new BufferedInputStream(fr); while (ki < size || ai < size) { StringBuffer sb = new StringBuffer(); for (; ; ) { int c = in.read(); if (c < 0) { if (ki < size) randomWords(key, ki, size); if (ai < size) randomWords(abs, ai, size); in.close(); return; } if (c == '\n') { String s = sb.toString(); if (ki < size) key[ki++] = s; else abs[ai++] = s; break; } sb.append((char) c); } } in.close(); } catch (IOException ex) { System.out.println("Can't read words file:" + ex); throw new Error(ex); } }
/** Renvoi la chaine correspondant au hash md5 du fichier */ private String computeHash() { try { FileInputStream reader_tmp = new FileInputStream(this); BufferedInputStream reader = new BufferedInputStream(reader_tmp); byte[] buffer = new byte[2048]; MessageDigest hash = MessageDigest.getInstance("MD5"); int count; do { count = reader.read(buffer); if (count > 0) { hash.update(buffer, 0, count); } } while (count != -1); byte[] b = hash.digest(); reader.close(); String result = ""; for (int i = 0; i < b.length; i++) { result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1); } return result; } catch (Exception e) { System.out.println("Unable to compute key for complete file"); e.printStackTrace(); } return new String(); }
private String readLine4Big() throws Exception { byte[] b = new byte[1024 * 256]; int i = 0; int readLen = 0; while ((readLen = bis.read(b, 0, 1024 * 256)) != -1) { if (readLen == 1) { if (b[0] == 10) { break; } else if (b[0] != 13) { this.bos.write(b, 0, readLen); } } else if (b[readLen - 2] != 13 && b[readLen - 1] != 10) { this.bos.write(b, 0, readLen); } else if (b[readLen - 1] == 10) { if (b[readLen - 2] == 13) { this.bos.write(b, 0, (readLen - 2)); } else { this.bos.write(b, 0, (readLen - 1)); } break; } } String ret = this.bos.toString(); this.bos.reset(); return ret; }
/** * Load UTF8withBOM or any ansi text file. * * @param filename * @return * @throws java.io.IOException */ public static String loadFileAsString(String filename) throws java.io.IOException { final int BUFLEN = 1024; BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN); byte[] bytes = new byte[BUFLEN]; boolean isUTF8 = false; int read, count = 0; while ((read = is.read(bytes)) != -1) { if (count == 0 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { isUTF8 = true; baos.write(bytes, 3, read - 3); // drop UTF8 bom marker } else { baos.write(bytes, 0, read); } count += read; } return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray()); } finally { try { is.close(); } catch (Exception ex) { } } }
public TestType1CFont(InputStream is) throws IOException { super(); setPreferredSize(new Dimension(800, 800)); addKeyListener(this); BufferedInputStream bis = new BufferedInputStream(is); int count = 0; ArrayList<byte[]> al = new ArrayList<byte[]>(); byte b[] = new byte[32000]; int len; while ((len = bis.read(b, 0, b.length)) >= 0) { byte[] c = new byte[len]; System.arraycopy(b, 0, c, 0, len); al.add(c); count += len; b = new byte[32000]; } data = new byte[count]; len = 0; for (int i = 0; i < al.size(); i++) { byte from[] = al.get(i); System.arraycopy(from, 0, data, len, from.length); len += from.length; } pos = 0; // printData(); parse(); // TODO: free up (set to null) unused structures (data, subrs, stack) }
private void sendFile(String filePath) { try { File fileToSend = new File(filePath); FileInputStream fileInputStream = new FileInputStream(fileToSend); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); OutputStream outputStream = clientSocket.getOutputStream(); // Writer: byte[] writerBuffer = new byte[(int) fileToSend.length()]; bufferedInputStream.read(writerBuffer, 0, writerBuffer.length); System.out.println("Sending " + filePath + "(" + writerBuffer.length + " bytes)"); outputStream.write("HTTP/1.1 200 OK\r\n\r\n".getBytes()); // System.out.println("Writing: "+new String(writerBuffer)); outputStream.write(writerBuffer, 0, writerBuffer.length); outputStream.flush(); System.out.println("Done."); // inputStream.close(); fileInputStream.close(); bufferedInputStream.close(); outputStream.close(); } catch (IOException e) { // report exception somewhere. e.printStackTrace(); } }
/** * Reads color table as 256 RGB integer values * * @param ncolors int number of colors to read * @return int array containing 256 colors (packed ARGB with full alpha) */ protected int[] readColorTable(int ncolors) { int nbytes = 3 * ncolors; int[] tab = null; byte[] c = new byte[nbytes]; int n = 0; try { n = in.read(c); } catch (IOException e) { } if (n < nbytes) { status = STATUS_FORMAT_ERROR; } else { tab = new int[256]; // max size to avoid bounds checks int i = 0; int j = 0; while (i < ncolors) { int r = ((int) c[j++]) & 0xff; int g = ((int) c[j++]) & 0xff; int b = ((int) c[j++]) & 0xff; tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b; } } return tab; }
// Send File public void sendFile(String chunkName) throws IOException { OutputStream os = null; String currentDir = System.getProperty("user.dir"); chunkName = currentDir + "/src/srcFile/" + chunkName; File myFile = new File(chunkName); byte[] arrby = new byte[(int) myFile.length()]; try { FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(arrby, 0, arrby.length); os = csocket.getOutputStream(); System.out.println("Sending File."); os.write(arrby, 0, arrby.length); os.flush(); System.out.println("File Sent."); // os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // os.close(); } }
/** @throws IOException If failed. */ private void initFavicon() throws IOException { assert favicon == null; InputStream in = getClass().getResourceAsStream("favicon.ico"); if (in != null) { BufferedInputStream bis = new BufferedInputStream(in); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { byte[] buf = new byte[2048]; while (true) { int n = bis.read(buf); if (n == -1) break; bos.write(buf, 0, n); } favicon = bos.toByteArray(); } finally { U.closeQuiet(bis); } } }
public static boolean download( URL url, String file, int prefix, int totalFilesize, IProgressUpdater updater) { File fFile = new File(new File(file).getParentFile().getPath()); if (!fFile.exists()) fFile.mkdirs(); boolean downloaded = true; BufferedInputStream in = null; FileOutputStream out = null; BufferedOutputStream bout = null; try { int count; int totalCount = 0; byte data[] = new byte[BUFFER]; in = new BufferedInputStream(url.openStream()); out = new FileOutputStream(file); bout = new BufferedOutputStream(out); while ((count = in.read(data, 0, BUFFER)) != -1) { bout.write(data, 0, count); totalCount += count; if (updater != null) updater.update(prefix + totalCount, totalFilesize); } } catch (Exception e) { e.printStackTrace(); Utils.logger.log(Level.SEVERE, "Download error!"); downloaded = false; } finally { try { close(in); close(bout); close(out); } catch (Exception e) { e.printStackTrace(); } } return downloaded; }
public int read(byte[] buf) throws Exception { for (int i = 0; i < buf.length; i++) { bis.read(buf, i, 1); } return buf.length; }
/** Reads a single byte from the input stream. */ protected int read() { int curByte = 0; try { curByte = in.read(); } catch (IOException e) { status = STATUS_FORMAT_ERROR; } return curByte; }
public static void copy(String srcFileName, String dstFileName) { try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcFileName)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dstFileName)); byte[] bytes = new byte[1024]; int nb = in.read(bytes, 0, bytes.length); while (nb > 0) { out.write(bytes, 0, nb); nb = in.read(bytes, 0, bytes.length); } in.close(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } }
/** * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件 * * @param task * @return "ok" if download success (else return errmessage); */ static String download(DownloadTask task) { if (!openedStatus && show) openStatus(); URL url; HttpURLConnection conn; try { url = new URL(task.getOrigin()); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/" + Math.random()); if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求 conn.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"); // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229; // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800"); conn.setRequestProperty( "Cookie", "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800"); conn.setRequestProperty("Host", "www.imgjav.com"); } Path directory = Paths.get(task.getDest()).getParent(); if (!Files.exists(directory)) Files.createDirectories(directory); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } try (InputStream is = conn.getInputStream(); BufferedInputStream in = new BufferedInputStream(is); FileOutputStream fos = new FileOutputStream(task.getDest()); OutputStream out = new BufferedOutputStream(fos); ) { int length = conn.getContentLength(); if (length < 1) throw new IOException("length<1"); byte[] binary = new byte[length]; byte[] buff = new byte[65536]; int len; int index = 0; while ((len = in.read(buff)) != -1) { System.arraycopy(buff, 0, binary, index, len); index += len; allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了 task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%"); } out.write(binary); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } return "ok"; }
/** * Reads data from a file and writes it to an index. * * @param indexWriter the index to write to. * @param inputFile the input data for the process. * @throws IOException * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException */ private void readFile(IndexWriter indexWriter, File inputFile) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFile)); byte[] tempInt = new byte[4]; int tmp, tmpFeature, count = 0; byte[] temp = new byte[100 * 1024]; // read file hashFunctionsFileName length: while (in.read(tempInt, 0, 4) > 0) { Document d = new Document(); tmp = SerializationUtils.toInt(tempInt); // read file hashFunctionsFileName: in.read(temp, 0, tmp); String filename = new String(temp, 0, tmp); // normalize Filename to full path. filename = inputFile .getCanonicalPath() .substring(0, inputFile.getCanonicalPath().lastIndexOf(inputFile.getName())) + filename; d.add(new StringField(DocumentBuilder.FIELD_NAME_IDENTIFIER, filename, Field.Store.YES)); // System.out.print(filename); while ((tmpFeature = in.read()) < 255) { // System.out.print(", " + tmpFeature); LireFeature f = (LireFeature) Class.forName(Extractor.features[tmpFeature]).newInstance(); // byte[] length ... in.read(tempInt, 0, 4); tmp = SerializationUtils.toInt(tempInt); // read feature byte[] in.read(temp, 0, tmp); f.setByteArrayRepresentation(temp, 0, tmp); addToDocument(f, d, Extractor.featureFieldNames[tmpFeature]); // d.add(new StoredField(Extractor.featureFieldNames[tmpFeature], // f.getByteArrayRepresentation())); } if (run == 2) indexWriter.addDocument(d); docCount++; // if (count%1000==0) System.out.print('.'); // if (count%10000==0) System.out.println(" " + count); } in.close(); }
/** Download resource to the given file */ private boolean download(URL target, File file) { _log.addDebug("JarDiffHandler: Doing download"); boolean ret = true; boolean delete = false; // use bufferedstream for better performance BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(target.openStream()); out = new BufferedOutputStream(new FileOutputStream(file)); int read = 0; int totalRead = 0; byte[] buf = new byte[BUF_SIZE]; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); totalRead += read; } _log.addDebug("total read: " + totalRead); _log.addDebug("Wrote URL " + target.toString() + " to file " + file); } catch (IOException ioe) { _log.addDebug("Got exception while downloading resource: " + ioe); ret = false; if (file != null) delete = true; } finally { try { in.close(); in = null; } catch (IOException ioe) { _log.addDebug("Got exception while downloading resource: " + ioe); } try { out.close(); out = null; } catch (IOException ioe) { _log.addDebug("Got exception while downloading resource: " + ioe); } if (delete) { file.delete(); } } return ret; }
/** * Read file input stream to string value. * * @param inputStream * @return * @throws IOException */ public static String readToString(InputStream inputStream) throws IOException { BufferedInputStream reader = new BufferedInputStream(inputStream); StringBuilder builder = new StringBuilder(); byte[] contents = new byte[1024]; int bytesRead = 0; while ((bytesRead = reader.read(contents)) != -1) { builder.append(new String(contents, 0, bytesRead)); } return builder.toString(); }
/** * Downloads a Bundle file for a given bundle id. * * @param request HttpRequest * @param response HttpResponse * @throws IOException If fails sending back to the user response information */ public void downloadBundle(HttpServletRequest request, HttpServletResponse response) throws IOException { try { if (!APILocator.getLayoutAPI() .doesUserHaveAccessToPortlet("EXT_CONTENT_PUBLISHING_TOOL", getUser())) { response.sendError(401); return; } } catch (DotDataException e1) { Logger.error(RemotePublishAjaxAction.class, e1.getMessage(), e1); response.sendError(401); return; } Map<String, String> map = getURIParams(); response.setContentType("application/x-tgz"); String bid = map.get("bid"); PublisherConfig config = new PublisherConfig(); config.setId(bid); File bundleRoot = BundlerUtil.getBundleRoot(config); ArrayList<File> list = new ArrayList<File>(1); list.add(bundleRoot); File bundle = new File(bundleRoot + File.separator + ".." + File.separator + config.getId() + ".tar.gz"); if (!bundle.exists()) { response.sendError(500, "No Bundle Found"); return; } response.setHeader("Content-Disposition", "attachment; filename=" + config.getId() + ".tar.gz"); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(bundle)); byte[] buf = new byte[4096]; int len; while ((len = in.read(buf, 0, buf.length)) != -1) { response.getOutputStream().write(buf, 0, len); } } catch (Exception e) { Logger.warn(this.getClass(), "Error Downloading Bundle.", e); } finally { try { in.close(); } catch (Exception ex) { Logger.warn(this.getClass(), "Error Closing Stream.", ex); } } return; }
/** * Sends an input stream to the server. * * @param input xml input * @throws IOException I/O exception */ private void send(final InputStream input) throws IOException { final BufferedInputStream bis = new BufferedInputStream(input); final BufferedOutputStream bos = new BufferedOutputStream(out); for (int b; (b = bis.read()) != -1; ) { // 0x00 and 0xFF will be prefixed by 0xFF if (b == 0x00 || b == 0xFF) bos.write(0xFF); bos.write(b); } bos.write(0); bos.flush(); info = receive(); if (!ok()) throw new IOException(info); }
private final String getFileAsString(String filename) throws IOException { File file = new File(filename); if (!file.exists()) { logger.log(Level.ERROR, "template file " + filename + " does not exist"); System.exit(1); } final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); final byte[] bytes = new byte[(int) file.length()]; bis.read(bytes); bis.close(); return new String(bytes); }
/** * Copies a file or directory * * @param src the file or directory to copy * @param dest where copy * @throws IOException */ public static void copyFile(File src, File dest) throws IOException { if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[4096]; int len; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); }
// Take a tree of files starting in a directory in a zip file // and copy them to a disk directory, recreating the tree. private int unpackZipFile( File inZipFile, String directory, String parent, boolean suppressFirstPathElement) { int count = 0; if (!inZipFile.exists()) return count; parent = parent.trim(); if (!parent.endsWith(File.separator)) parent += File.separator; if (!directory.endsWith(File.separator)) directory += File.separator; File outFile = null; try { ZipFile zipFile = new ZipFile(inZipFile); Enumeration zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipEntries.nextElement(); String name = entry.getName().replace('/', File.separatorChar); if (name.startsWith(directory)) { if (suppressFirstPathElement) name = name.substring(directory.length()); outFile = new File(parent + name); // Create the directory, just in case if (name.indexOf(File.separatorChar) >= 0) { String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1); File dirFile = new File(parent + p); dirFile.mkdirs(); } if (!entry.isDirectory()) { System.out.println("Installing " + outFile); // Copy the file BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry)); int size = 1024; int n = 0; byte[] b = new byte[size]; while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n); in.close(); out.flush(); out.close(); // Count the file count++; } } } zipFile.close(); } catch (Exception e) { System.err.println("...an error occured while installing " + outFile); e.printStackTrace(); System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage()); return -count; } System.out.println(count + " files were installed."); return count; }
private String readFileAsString(File file) throws java.io.IOException { byte[] buffer = new byte[(int) file.length()]; BufferedInputStream bis = null; try { bis = new BufferedInputStream(new FileInputStream(file)); bis.read(buffer); } finally { if (bis != null) try { bis.close(); } catch (IOException ignored) { } } return new String(buffer); }
private String readLine() throws IOException { if (buffer == null) { buffer = new byte[512]; } int next; int count = 0; for (; ; ) { next = input.read(); if (next < 0 || next == '\n') break; if (next != '\r') { buffer[count++] = (byte) next; } if (count >= 512) throw new IOException("HTTP Header too long"); } return new String(buffer, 0, count); }
public void upload() throws Exception { boolean isMultipart = ServletFileUpload.isMultipartContent(this.request); if (!isMultipart) { this.state = this.errorInfo.get("NOFILE"); return; } if (this.inputStream == null) { this.state = this.errorInfo.get("FILE"); return; } // 存储title this.title = this.getParameter("pictitle"); try { String savePath = this.getFolder(this.savePath); if (!this.checkFileType(this.originalName)) { this.state = this.errorInfo.get("TYPE"); return; } this.fileName = this.getName(this.originalName); this.type = this.getFileExt(this.fileName); this.url = savePath + "/" + this.fileName; FileOutputStream fos = new FileOutputStream(this.getPhysicalPath(this.url)); BufferedInputStream bis = new BufferedInputStream(this.inputStream); byte[] buff = new byte[128]; int count = -1; while ((count = bis.read(buff)) != -1) { fos.write(buff, 0, count); } bis.close(); fos.close(); this.state = this.errorInfo.get("SUCCESS"); } catch (Exception e) { e.printStackTrace(); this.state = this.errorInfo.get("IO"); } }
private String readLine4Small() throws Exception { this.b[0] = (byte) 0; int i = 0; while (bis.read(this.b, 0, 1) != -1) { if (this.b[0] != 13 && this.b[0] != 10) { this.bos.write(this.b, 0, 1); } else if (this.b[0] == 10) { break; } } String ret = this.bos.toString(); this.bos.reset(); return ret; }
public static void readFile(File file, OutputStream out) { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; while( true ) { int count = in.read(buffer); if( count == -1 ) break; out.write(buffer, 0, count); } } catch(IOException e) { throw Log.errRTExcept(e); } finally { close(in); } }
/** * Funcion que transforma el archivo suministrado en un arreglo de bytes para transferir al * servidor de archivos * * @param nombreArchivo el nombre del archivo a comprobar * @return True si encuentra el archivo * @throws Exception Al ocurrir un error en transformar el archivo a bytes */ public static byte[] formatearArchivo(String nombreArchivo) { try { // Crear un arreglo de bytes con el tamaño del archivo File archivo = new File(nombreArchivo); byte buffer[] = new byte[(int) archivo.length()]; BufferedInputStream input = new BufferedInputStream(new FileInputStream(nombreArchivo)); input.read(buffer, 0, buffer.length); input.close(); return (buffer); } catch (Exception e) { String error = "- Error - Problema al transformar el archivo " + "en un arreglo de bytes"; System.out.print(error); return (null); } }
public BytecodeBuffer(String filename) throws IOException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(filename)); bytecodes = new byte[in.available()]; in.read(bytecodes); size = bytecodes.length; pos = 0; } finally { if (in != null) { try { in.close(); } catch (IOException ex) { } } } }