private void onOK() { try { InputStream in = new FileInputStream(inputFile); if (outputFile == null) { outputFile = new File(inputFile.getAbsolutePath() + "_"); } OutputStream out = new FileOutputStream(outputFile); ANSIUnicodeConverter converter = new ANSIUnicodeConverter(); converter.setDirection(ANSIUnicodeConverter.ANSI2UNICODE); StringBuffer output = new StringBuffer(); final int BUFFER_SIZE = 1024 * 1024; // 1M byte[] buffer = new byte[BUFFER_SIZE]; int currentPosition = 0; while (in.available() != 0) { int currentBufferSize = BUFFER_SIZE; if (in.available() < BUFFER_SIZE) { currentBufferSize = in.available(); } in.read(buffer, currentPosition, currentBufferSize); currentBufferSize = currentBufferSize + currentBufferSize; converter.setInput(new String(buffer)); out.write(converter.convert().getBytes()); } in.close(); out.close(); } catch (Exception e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
// Essentially links an InputStream to the proper channels in the log box. private static void printOutput(InputStream in, SimpleAttributeSet set) { int i = 0; String s = ""; try { while ((i = in.read()) != -1) { s += (char) i; // print(, set); } } catch (IOException io) { println("Error: IOException when reading InputStream " + in.toString(), progErr); } println(s); }
/** * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string * buffer to use ** @throws IOException if an error occurs or the server has stopped */ protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb) throws IOException { if (socket != null) { int dataLen = 0; StringBuffer data = (sb != null) ? sb : new StringBuffer(); InputStream input = socket.getInputStream(); while ((maxLen < 0) || (maxLen > dataLen)) { int ch = input.read(); // Print.logInfo("ReadLine char: " + ch); if (ch < 0) { // this means that the server has stopped throw new IOException("End of input"); } else if (ch == LineTerminatorChar) { // include line terminator in String data.append((char) ch); dataLen++; break; } else { // append character data.append((char) ch); dataLen++; } } return data.toString(); } else { return null; } }
private final String readMSG(final int len) throws IOException, InterruptedException, MessagingNetworkException { if (len > 65000) ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes"); byte[] b = new byte[len]; InputStream is = getInputStream(); synchronized (is) { long abortTime = System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS; int ofs = 0; while (ofs < len) { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); int read = is.read(b, ofs, len - ofs); if (read < 0) read = 0; ofs += read; if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out"); /* if (len >= buffer.length) { ... return ...; } int pos = findCRLF(); if (pos != -1) break; fill(is, abortTime); */ } String msg = new String(b, 0, len, "UTF-8"); return msg; } }
public void run() { try { final byte[] lBuf = new byte[1024]; int lBytesRead; while (in.read(lBuf, 0, 1) != -1) { synchronized (JConsole.this) { lBytesRead = in.read(lBuf, 1, 1023) + 1; print(new String(lBuf, 0, lBytesRead), attr); while (in.available() > 0) { lBytesRead = in.read(lBuf); print(new String(lBuf, 0, lBytesRead), attr); } } } } catch (IOException e) { e.printStackTrace(); } }
public final String readCommand(byte[] b) throws IOException, InterruptedException, MessagingNetworkException { InputStream is = getInputStream(); synchronized (is) { long abortTime = System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS; int ofs = 0; boolean d = false; for (; ; ) { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); int by = is.read(); if (by == -1) throw new IOException("unexpected EOF"); if (by == 10 && d) break; d = (by == 13); if (ofs < b.length) { b[ofs++] = (byte) by; } if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out"); /* if (len >= buffer.length) { ... return ...; } int pos = findCRLF(); if (pos != -1) break; fill(is, abortTime); */ } if (b[ofs - 1] == 13) --ofs; String line = new String(b, 0, ofs, "ASCII"); if (StringUtil.startsWith(line, "MSG")) { StringTokenizer st = new StringTokenizer(line); String len_s = null; while (st.hasMoreTokens()) { len_s = st.nextToken(); } if (len_s == null) throw new AssertException("len_s is null"); int len; try { len = Integer.parseInt(len_s); } catch (NumberFormatException ex) { ServerConnection.throwProtocolViolated("MSG length must be int"); len = 0; } String msg = readMSG(len); line = line + "\r\n" + msg; } if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("S: " + line); return line; } }
/** * Copy data from an input stream to an output stream. * * @param in Input stream. * @param out Output stream. * @throws IOException */ public static void copy(InputStream in, OutputStream out) throws IOException { // Do not allow other threads to read from the // input or write to the output while copying is // taking place synchronized (in) { synchronized (out) { byte[] buffer = new byte[1024]; while (true) { int bytesRead = in.read(buffer); if (bytesRead == -1) break; out.write(buffer, 0, bytesRead); } } } }
Ps2RealityControlCenter(String dir) throws IOException { try { byte[] abIcon; InputStream inputstreamIcon = this.getClass().getResourceAsStream("icon.gif"); int iIconSize = inputstreamIcon.available(); abIcon = new byte[iIconSize]; inputstreamIcon.read(abIcon); this.setIconImage(new ImageIcon(abIcon).getImage()); } catch (Exception ex) { // the default icon will be used } panelChooser = new Ps2RealityFileChooser(dir); }
/** * ** Reads the specified number of bytes from the specifed socket ** @param socket The socket * from which bytes are read ** @param length The number of bytes to read from the socket * ** @throws IOException if an error occured or the server has stopped */ protected static byte[] socketReadBytes(Socket socket, int length) throws IOException { if (socket == null) { return null; } else if (length <= 0) { return new byte[0]; } else { int dataLen = 0; byte data[] = new byte[length]; InputStream input = socket.getInputStream(); while (dataLen < length) { int ch = input.read(); if (ch < 0) { // this means that the server has stopped throw new IOException("End of input"); } else { data[dataLen] = (byte) ch; dataLen++; } } return data; } }
private static void copyfile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); // For Overwrite the file. OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); EIError.debugMsg("File copied " + srFile + " " + dtFile, EIError.ErrorLevel.Notice); } catch (Exception e) { EIError.debugMsg( "Couldn't copy file" + srFile + " " + dtFile + " " + e.getMessage(), EIError.ErrorLevel.Error); } }
// Deal with something robot has sent. public void serialEvent(SerialPortEvent events) { switch (events.getEventType()) { case SerialPortEvent.DATA_AVAILABLE: try { final byte[] buffer = new byte[1024]; int len = in.read(buffer); if (len > 0) { String line2 = new String(buffer, 0, len); Log("<span style='color:#FFA500'>" + line2.replace("\n", "<br>") + "</span>"); line3 += line2; // wait for the cue ("> ") to send another command if (line3.lastIndexOf(cue) != -1) { if (ConfirmPort()) { line3 = ""; SendFileCommand(); } } } } catch (IOException e) { } break; } }
/** * ** Reads the bytes from the specifed socket until an eod-of-stream error occurs, or ** until * the maximum number of bytes has bee read. ** @param socket The socket from which bytes are read * ** @param baos The ByteArrayOutputStream to which the bytes are written ** @param maxLength The * number of bytes to read from the socket ** @return The number of bytes read if no exception has * occurred ** @throws IOException if an error occured or the server has stopped */ protected static int socketReadBytes(Socket socket, ByteArrayOutputStream baos, int maxLength) throws IOException { if (socket == null) { return 0; } else if (maxLength == 0) { return 0; } else { int dataLen = 0; InputStream input = socket.getInputStream(); while ((maxLength < 0) || (dataLen < maxLength)) { int ch = input.read(); if (ch < 0) { // we've reached the end of input return dataLen; } else { if (baos != null) { baos.write(ch); } dataLen++; } } return dataLen; } }
/** Determine JDK level of an applet. */ private void findAppletJDKLevel(Applet applet) { // To determine the JDK level of an applet, the // most reliable way is to check the major version // of the applet class file. // synchronized on applet class object, so calling from // different instances of the same applet will be // serialized. Class<?> appletClass = applet.getClass(); synchronized (appletClass) { // Determine if the JDK level of an applet has been // checked before. Boolean jdk11Target = loader.isJDK11Target(appletClass); Boolean jdk12Target = loader.isJDK12Target(appletClass); // if applet JDK level has been checked before, retrieve // value and return. if (jdk11Target != null || jdk12Target != null) { jdk11Applet = (jdk11Target == null) ? false : jdk11Target.booleanValue(); jdk12Applet = (jdk12Target == null) ? false : jdk12Target.booleanValue(); return; } String name = appletClass.getName(); // first convert any '.' to '/' name = name.replace('.', '/'); // append .class final String resourceName = name + ".class"; byte[] classHeader = new byte[8]; try (InputStream is = AccessController.doPrivileged( (PrivilegedAction<InputStream>) () -> loader.getResourceAsStream(resourceName))) { // Read the first 8 bytes of the class file int byteRead = is.read(classHeader, 0, 8); // return if the header is not read in entirely // for some reasons. if (byteRead != 8) return; } catch (IOException e) { return; } // Check major version in class file header int major_version = readShort(classHeader, 6); // Major version in class file is as follows: // 45 - JDK 1.1 // 46 - JDK 1.2 // 47 - JDK 1.3 // 48 - JDK 1.4 // 49 - JDK 1.5 if (major_version < 46) jdk11Applet = true; else if (major_version == 46) jdk12Applet = true; // Store applet JDK level in AppContext for later lookup, // e.g. page switch. loader.setJDK11Target(appletClass, jdk11Applet); loader.setJDK12Target(appletClass, jdk12Applet); } }
public static boolean showLicensing() { if (Config.getLicenseResource() == null) return true; ClassLoader cl = Main.class.getClassLoader(); URL url = cl.getResource(Config.getLicenseResource()); if (url == null) return true; String license = null; try { URLConnection con = url.openConnection(); int size = con.getContentLength(); byte[] content = new byte[size]; InputStream in = new BufferedInputStream(con.getInputStream()); in.read(content); license = new String(content); } catch (IOException ioe) { Config.trace("Got exception when reading " + Config.getLicenseResource() + ": " + ioe); return false; } // Build dialog JTextArea ta = new JTextArea(license); ta.setEditable(false); final JDialog jd = new JDialog(_installerFrame, true); Container comp = jd.getContentPane(); jd.setTitle(Config.getLicenseDialogTitle()); comp.setLayout(new BorderLayout(10, 10)); comp.add(new JScrollPane(ta), "Center"); Box box = new Box(BoxLayout.X_AXIS); box.add(box.createHorizontalStrut(10)); box.add(new JLabel(Config.getLicenseDialogQuestionString())); box.add(box.createHorizontalGlue()); JButton acceptButton = new JButton(Config.getLicenseDialogAcceptString()); JButton exitButton = new JButton(Config.getLicenseDialogExitString()); box.add(acceptButton); box.add(box.createHorizontalStrut(10)); box.add(exitButton); box.add(box.createHorizontalStrut(10)); jd.getRootPane().setDefaultButton(acceptButton); Box box2 = new Box(BoxLayout.Y_AXIS); box2.add(box); box2.add(box2.createVerticalStrut(5)); comp.add(box2, "South"); jd.pack(); final boolean accept[] = new boolean[1]; acceptButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { accept[0] = true; jd.hide(); jd.dispose(); } }); exitButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { accept[0] = false; jd.hide(); jd.dispose(); } }); // Apply any defaults the user may have, constraining to the size // of the screen, and default (packed) size. Rectangle size = new Rectangle(0, 0, 500, 300); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); size.width = Math.min(screenSize.width, size.width); size.height = Math.min(screenSize.height, size.height); // Center the window jd.setBounds( (screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2, size.width, size.height); // Show dialog jd.show(); return accept[0]; }
/** Unpacks a resource to a temp. file */ public static File unpackInstaller(String resourceName) { // Array to hold all results (this code is slightly more // generally that it needs to be) File[] results = new File[1]; URL[] urls = new URL[1]; // Determine size of download ClassLoader cl = Main.class.getClassLoader(); urls[0] = cl.getResource(Config.getInstallerResource()); if (urls[0] == null) { Config.trace("Could not find resource: " + Config.getInstallerResource()); return null; } int totalSize = 0; int totalRead = 0; for (int i = 0; i < urls.length; i++) { if (urls[i] != null) { try { URLConnection connection = urls[i].openConnection(); totalSize += connection.getContentLength(); } catch (IOException ioe) { Config.trace("Got exception: " + ioe); return null; } } } // Unpack each file for (int i = 0; i < urls.length; i++) { if (urls[i] != null) { // Create temp. file to store unpacked file in InputStream in = null; OutputStream out = null; try { // Use extension from URL (important for dll files) String extension = new File(urls[i].getFile()).getName(); int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1; if (lastdotidx == -1) { extension = ".dat"; } else { extension = extension.substring(lastdotidx); } // Create output stream results[i] = File.createTempFile("jre", extension); results[i].deleteOnExit(); out = new FileOutputStream(results[i]); // Create inputstream URLConnection connection = urls[i].openConnection(); in = connection.getInputStream(); int read = 0; byte[] buf = new byte[BUFFER_SIZE]; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); // Notify delegate totalRead += read; if (totalRead > totalSize && totalSize != 0) totalSize = totalRead; // Update UI if (totalSize != 0) { int percent = (100 * totalRead) / totalSize; setStepText(STEP_UNPACK, Config.getWindowStepProgress(STEP_UNPACK, percent)); } } } catch (IOException ie) { Config.trace("Got exception while downloading resource: " + ie); for (int j = 0; j < results.length; j++) { if (results[j] != null) results[j].delete(); } return null; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException io) { /* ignore */ } } } } setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK)); return results[0]; }