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. } }
protected void runScript(String[] cmd, JTextArea txaMsg) { String strg = ""; if (cmd == null) return; Process prcs = null; try { Messages.postDebug("Running script: " + cmd[2]); Runtime rt = Runtime.getRuntime(); prcs = rt.exec(cmd); if (prcs == null) return; InputStream istrm = prcs.getInputStream(); if (istrm == null) return; BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm)); while ((strg = bfr.readLine()) != null) { // System.out.println(strg); strg = strg.trim(); // Messages.postDebug(strg); strg = strg.toLowerCase(); if (txaMsg != null) { txaMsg.append(strg); txaMsg.append("\n"); } } } catch (Exception e) { // e.printStackTrace(); Messages.writeStackTrace(e); Messages.postDebug(e.toString()); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. try { if (prcs != null) { OutputStream os = prcs.getOutputStream(); if (os != null) os.close(); InputStream is = prcs.getInputStream(); if (is != null) is.close(); is = prcs.getErrorStream(); if (is != null) is.close(); } } catch (Exception ex) { Messages.writeStackTrace(ex); } } }
void writeNcstream(String filename) { try { NcStreamWriter writer = new NcStreamWriter(ds, null); OutputStream fos = new BufferedOutputStream(new FileOutputStream(filename), 50 * 1000); writer.streamAll(fos); fos.close(); JOptionPane.showMessageDialog(this, "File successfully written"); } catch (Exception ioe) { JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage()); ioe.printStackTrace(); } }
public void save(ActionEvent e) { if (file == null) { saveAs(e); } try { OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); wordList.store(out, "Generated by JWordPlay"); out.flush(); out.close(); } catch (IOException ex) { handleException(ex); } }
/** * Upload files to pre-configured url. * * @param uploadLocation the location we are uploading to. * @param fileName the filename we use for the resulting filename we upload. * @param params the optional parameter names. * @param values the optional parameter values. */ static void uploadLogs(String uploadLocation, String fileName, String[] params, String[] values) { try { File tempDir = LoggingUtilsActivator.getFileAccessService().getTemporaryDirectory(); File newDest = new File(tempDir, fileName); File optionalFile = null; // if we have some description params // save them to file and add it to archive if (params != null) { optionalFile = new File( LoggingUtilsActivator.getFileAccessService().getTemporaryDirectory(), "description.txt"); OutputStream out = new FileOutputStream(optionalFile); for (int i = 0; i < params.length; i++) { out.write((params[i] + " : " + values[i] + "\r\n").getBytes("UTF-8")); } out.flush(); out.close(); } newDest = LogsCollector.collectLogs(newDest, optionalFile); // don't leave any unneeded information if (optionalFile != null) optionalFile.delete(); if (uploadLocation == null) return; if (HttpUtils.postFile(uploadLocation, "logs", newDest) != null) { NotificationService notificationService = LoggingUtilsActivator.getNotificationService(); if (notificationService != null) { ResourceManagementService resources = LoggingUtilsActivator.getResourceService(); String bodyMsgKey = "plugin.loggingutils.ARCHIVE_MESSAGE_OK"; notificationService.fireNotification( LOGFILES_ARCHIVED, resources.getI18NString("plugin.loggingutils.ARCHIVE_BUTTON"), resources.getI18NString(bodyMsgKey, new String[] {uploadLocation}), null); } } } catch (Throwable e) { logger.error("Cannot upload file", e); } }
public void ClosePort() { if (portOpened) { if (serialPort != null) { try { // Close the I/O streams. out.close(); in.close(); // Close the port. serialPort.removeEventListener(); serialPort.close(); } catch (IOException e) { // Don't care } } ClearLog(); portOpened = false; portConfirmed = false; previewPane.setConnected(false); UpdateMenuBar(); } }
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); } }
@Override public void run() { try { // Create data input and output streams DataInputStream inputFromClient = new DataInputStream(socket.getInputStream()); DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream()); // Set up a byte buffer to capture the file from the client byte[] buffer = new byte[BUFFER_SIZE]; OutputStream outputStream = null; String fileName = ""; boolean createFile = true; int bytesReceived = 0; long totalBytesReceived = 0; long fileSize = 0; // Continuously serve the client while (true) { bytesReceived = inputFromClient.read(buffer); if (bytesReceived > 0) { // Get the file transmission header from the initial client packet String transmitHeader = new String(buffer, 0, bytesReceived); // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().; String[] header = transmitHeader.split(HEADER_DEL); fileSize = Long.parseLong(header[0]); fileName = header[1]; // Send receipt acknowledgment back to the client. Just send back the number of bytes // received. outputToClient.writeInt(bytesReceived); // Reinitialize buffer values buffer = new byte[BUFFER_SIZE]; bytesReceived = 0; } // Wait for client to send bytes while ((bytesReceived = inputFromClient.read(buffer)) != -1) { if (inputFromClient.available() > 0) { if (createFile) { // Get a unique name for the file to be received fileName = textFolder.getText() + fileName; // getUniqueFileName(); outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } // Write bytes to file outputStream.write(buffer, 0, bytesReceived); } else { // We get here if no more data is available, but some bytes were already // received // If bytes were received and the file wasn't already created, // it means that the file was smaller than our buffer size. // Create the file... if (bytesReceived > 0 && createFile) { // Get a unique name for the file to be received fileName = textFolder.getText() + fileName; // getUniqueFileName(); outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } if (outputStream != null) { if (bytesReceived > 0) { // Write remaining bytes to file, if any outputStream.write(buffer, 0, bytesReceived); } outputStream.flush(); outputStream.close(); textArea.append("Received file successfully. Saved as " + fileName + "\n"); // Return success to client. outputToClient.writeInt(0); } // Reset creation flag createFile = true; break; } // Reinitialize buffer values buffer = new byte[BUFFER_SIZE]; bytesReceived = 0; } } } catch (IOException e) { System.err.println(e); } }
@Override public void run() { try { // Create a packet for sending data DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length); OutputStream outputStream = null; String fileName = ""; boolean createFile = true; int bytesReceived = 0; long totalBytesReceived = 0; long fileSize = 0; socket.receive(receivePacket); // Display the client number textArea.append("Starting thread for UDP client " + clientNo + " at " + new Date() + '\n'); textArea.append( "The client host name is " + receivePacket.getAddress().getHostName() + " and port number is " + receivePacket.getPort() + '\n'); // Continuously serve the client while (true) { bytesReceived = receivePacket.getLength(); if (bytesReceived > 0) { // Get the file transmission header from the initial client packet String transmitHeader = new String(receivePacket.getData(), 0, bytesReceived); // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().; String[] header = transmitHeader.split(HEADER_DEL); fileSize = Long.parseLong(header[0]); fileName = header[1]; // Send receipt acknowledgment back to the client. Just send back the number of bytes // received. setSendPacketAddress(sendPacket, receivePacket); sendPacket.setData(String.valueOf(bytesReceived).getBytes()); socket.send(sendPacket); } while (totalBytesReceived < fileSize) { // Wait for client to send bytes // socket.setSendBufferSize(BUFFER_SIZE); socket.receive(receivePacket); bytesReceived = receivePacket.getLength(); if (totalBytesReceived == 0) { if (createFile) { // Get a unique name for the file to be received // fileName = getUniqueFileName(); fileName = textFolder.getText() + fileName; outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } // Write bytes to file outputStream.write(receivePacket.getData(), 0, bytesReceived); } else { if (outputStream != null) { // Write bytes to file, if any outputStream.write(receivePacket.getData(), 0, bytesReceived); } } // Increment total bytes received totalBytesReceived += bytesReceived; // Tell the client to send more data. Just send back the number of bytes received. sendPacket.setData(String.valueOf(bytesReceived).getBytes()); socket.send(sendPacket); // buffer = new byte[BUFFER_SIZE]; Arrays.fill(buffer, (byte) 0); receivePacket = new DatagramPacket(buffer, buffer.length); } outputStream.flush(); outputStream.close(); textArea.append("Received file successfully. Saved as " + fileName + "\n"); // Tell the client transmission is complete. Just send back the total number of bytes // received. sendPacket.setData(String.valueOf(totalBytesReceived).getBytes()); socket.send(sendPacket); // Reset creation flag createFile = true; totalBytesReceived = 0; // Wait for client to send another file socket.receive(receivePacket); } } catch (IOException e) { System.err.println(e); } }
/** 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]; }