/** * Construct a frequency table from an InputStream. This will create a temporary file to copy the * InputStream in. * * @param source the Input Stream * @return an InputStream which is a copy of the source Stream, provided to re-Read the same Bytes * for the actual compression process. */ public InputStream constructTable(InputStream source, boolean copy) { freq = new int[TABLESIZE]; try { File file = null; FileOutputStream fos = null; if (copy == true) { file = File.createTempFile("huf", "tmp"); file.deleteOnExit(); fos = new FileOutputStream(file); } while (source.available() != 0) { int c = source.read(); freq[c]++; if (copy) fos.write(c); } source.close(); if (copy) { fos.close(); return new FileInputStream(file); } return null; } catch (Exception ex) { ExHandler.handle(ex); return null; } }
private static void testSysOut(String fs, String exp, Object... args) { FileOutputStream fos = null; FileInputStream fis = null; try { PrintStream saveOut = System.out; fos = new FileOutputStream("testSysOut"); System.setOut(new PrintStream(fos)); System.out.format(Locale.US, fs, args); fos.close(); fis = new FileInputStream("testSysOut"); byte[] ba = new byte[exp.length()]; int len = fis.read(ba); String got = new String(ba); if (len != ba.length) fail(fs, exp, got); ck(fs, exp, got); System.setOut(saveOut); } catch (FileNotFoundException ex) { fail(fs, ex.getClass()); } catch (IOException ex) { fail(fs, ex.getClass()); } finally { try { if (fos != null) fos.close(); if (fis != null) fis.close(); } catch (IOException ex) { fail(fs, ex.getClass()); } } }
/** * @param in the InputStream, i.e. the source, closes the passed input stream * @param fn where to output the file (numbers are ok) */ protected final void fileForShow(InputStream in, String fn) { File f = (((fn == null) || fn.equals("")) ? DEF_FILE : getFile(fn)); boolean fout = "true".equals(System.getProperty("file.echo")); try { FileOutputStream out = new FileOutputStream(f); int b = 0; while ((b = in.read()) != -1) { if (fout) { Console.out.write(b); } out.write(b); } out.flush(); out.close(); Console.out.flush(); in.close(); s_showFile = f; } catch (Exception exp) { System.err.println("FAILED TO WRITE TO OUTPUT FILE " + f.getAbsolutePath()); exp.printStackTrace(); } }
/** * This method will read the standard input and save the content to a temporary. source file since * the source file will be parsed mutiple times. The HTML source file is parsed and checked for * Charset in HTML tags at first time, then source file is parsed again for the converting The * temporary file is read from standard input and saved in current directory and will be deleted * after the conversion has completed. * * @return the vector of the converted temporary source file name */ public Vector getStandardInput() throws FileAccessException { byte[] buf = new byte[2048]; int len = 0; FileInputStream fis = null; FileOutputStream fos = null; File tempSourceFile; String tmpSourceName = ".tmpSource_stdin"; File outFile = new File(tmpSourceName); tempSourceFile = new File(System.getProperty("user.dir") + sep + tmpSourceName); if (!tempSourceFile.exists()) { try { fis = new FileInputStream(FileDescriptor.in); fos = new FileOutputStream(outFile); while ((len = fis.read(buf, 0, 2048)) != -1) fos.write(buf, 0, len); } catch (IOException e) { System.out.println(ResourceHandler.getMessage("plugin_converter.write_permission")); return null; } } else { throw new FileAccessException(ResourceHandler.getMessage("plugin_converter.overwrite")); } tempSourceFile = new File(System.getProperty("user.dir") + sep + tmpSourceName); if (tempSourceFile.exists()) { fileSpecs.add(tmpSourceName); return fileSpecs; } else { throw new FileAccessException( ResourceHandler.getMessage("plugin_converter.write_permission")); } }
/** * @param guid * @param data * @throws IOException */ public void write(int guid, byte[] data) throws IOException { File file = new File(Integer.toString(guid)); FileOutputStream fos = null; fos = new FileOutputStream(file); // Writes bytes from the specified byte array to this file output stream fos.write(data); }
/** * Créer le fichier complet correspondant Copie et réassemble les données Supprime le fichier * temporaire et renvoi le nouveau fichier */ public synchronized FileShared tmpToComplete() { String name = this.getName(); name = name.substring(0, name.length() - ((String) App.config.get("tmpExtension")).length()); File complete = new File(App.config.get("downloadDir") + File.separator + name); if (complete.exists()) { throw new IllegalArgumentException(); } try { FileOutputStream writer_tmp = new FileOutputStream(complete, true); FileChannel writer = writer_tmp.getChannel(); int i; for (i = 0; i < this.nbPieces(); i++) { byte[] piece = this.readPieceTmpFile(i); Tools.write(writer, 0, piece); } writer.force(true); writer_tmp.close(); } catch (Exception e) { System.out.println("Unable to write complete file"); e.printStackTrace(); } this.delete(); return new FileShared(name); }
/** Initialise le header du fichier temporaire */ private void initHeaderTmpFile() { try { FileOutputStream writer_tmp = new FileOutputStream(this); FileChannel writer = writer_tmp.getChannel(); int offset = 0; // Taille de la clef Tools.write(writer, offset, _key.length()); offset += 4; // Clef Tools.write(writer, offset, _key); offset += _key.length(); // Size Tools.write(writer, offset, _size); offset += 4; // piecesize Tools.write(writer, offset, _piecesize); offset += 4; // Buffermap int i; for (i = 0; i < this.nbPieces(); i++) { Tools.write(writer, offset, -1); offset += 4; } writer.force(true); writer_tmp.close(); } catch (Exception e) { System.out.println("Unable to create a new tmp file"); e.printStackTrace(); } }
public static void saveJPG(Image img, String s) { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, null, null); FileOutputStream out = null; try { out = new FileOutputStream(s); } catch (java.io.FileNotFoundException io) { System.out.println("File Not Found"); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi); param.setQuality(0.5f, false); encoder.setJPEGEncodeParam(param); try { encoder.encode(bi); out.close(); } catch (java.io.IOException io) { System.out.println("IOException"); } }
// Merge the availableChunks to build the original file void MergeChunks(File[] chunks) throws IOException { // Safety check if (chunks == null) { System.err.println("ERROR: No chunks to merge!"); return; } FileOutputStream fos = new FileOutputStream("complete/" + filename); try { FileInputStream fis; byte[] fileBytes; int bytesRead; for (File f : chunks) { fis = new FileInputStream(f); fileBytes = new byte[(int) f.length()]; bytesRead = fis.read(fileBytes, 0, (int) f.length()); assert (bytesRead == fileBytes.length); assert (bytesRead == (int) f.length()); fos.write(fileBytes); fos.flush(); fileBytes = null; fis.close(); fis = null; } } catch (Exception exception) { exception.printStackTrace(); } finally { fos.close(); fos = null; } }
protected void add(Object value) { File f = null; FileOutputStream fos = null; try { f = createTempFile("S", dir); fos = new FileOutputStream(f); ObjectOutputStream fout = new ObjectOutputStream(new BufferedOutputStream(fos)); fout.writeObject(value); fout.flush(); fos.getFD().sync(); } catch (Exception e) { throw new SpaceError(e); } finally { if (fos != null) { try { fos.close(); } catch (Exception e) { throw new SpaceError(e); } } } stored.add(f.getAbsolutePath()); /* fill cache */ if (cacheSize > data.size()) if ((data.size() + 1) == stored.size()) data.add(value); }
static void eliminarLugarFicheroLOC(Lugar lugar) { String fichero = lugar.getFicheroLOC(); try { FileReader fr = new FileReader(fichero); BufferedReader br = new BufferedReader(fr); String linea; ArrayList lineas = new ArrayList(); do { linea = br.readLine(); if (linea != null) { if (!linea.substring(0, lugar.nombre.length()).equals(lugar.nombre)) lineas.add(linea); } else break; } while (true); br.close(); fr.close(); FileOutputStream fos = new FileOutputStream(fichero); PrintWriter pw = new PrintWriter(fos); for (int i = 0; i < lineas.size(); i++) pw.println((String) lineas.get(i)); pw.flush(); pw.close(); fos.close(); } catch (FileNotFoundException e) { System.err.println("error: eliminando " + e); } catch (IOException e) { System.err.println("error: eliminando 2 : " + e); } }
public static void writeLogFile(String descript, String filename) { File file; FileOutputStream outstream; // BufferedWriter outstream; Date time = new Date(); long bytes = 30000000; try { // Get log file String logfile = "C:\\" + filename + ".txt"; file = new File(logfile); boolean exists = file.exists(); if (!exists) { // create a new, empty node file try { file = new File(logfile); boolean success = file.createNewFile(); } catch (IOException e) { System.out.println("Create Event Log file failed!"); } } try { descript = descript + "\n"; outstream = new FileOutputStream(file, true); for (int i = 0; i < descript.length(); ++i) { outstream.write((byte) descript.charAt(i)); } outstream.close(); } catch (IOException e) { } } catch (java.lang.Exception e) { } }
void ReceiveFile() throws Exception { String fileName; fileName = din.readUTF(); if (fileName != null && !fileName.equals("NOFILE")) { System.out.println("Receiving File"); File f = new File( System.getProperty("user.home") + "/Desktop" + "/" + fileName.substring(fileName.lastIndexOf("/") + 1)); System.out.println(f.toString()); f.createNewFile(); FileOutputStream fout = new FileOutputStream(f); int ch; String temp; do { temp = din.readUTF(); ch = Integer.parseInt(temp); if (ch != -1) { fout.write(ch); } } while (ch != -1); System.out.println("Received File : " + fileName); fout.close(); } else { } }
public void flush() throws IOException { if (!dirty) return; FileOutputStream fos = null; OutputStreamWriter osw = null; try { fos = new FileOutputStream(filePath); osw = new OutputStreamWriter(fos, charset); // 全局数据 for (Line l : globalLines) { osw.write(l.toString()); osw.write('\n'); } // 各个块 for (Sector s : sectors) { osw.write(s.toString()); } dirty = false; } finally { // XXX 因为stream之间有一定的依赖顺序,必须按照一定的顺序关闭流 if (osw != null) osw.close(); if (fos != null) fos.close(); } }
/** * Save the downloaded files into the corresponding directories * * @deprecated */ public synchronized void save() { synchronized (this) { synchronized (this.isComplete) { byte[] data = new byte[0]; for (int i = 0; i < this.nbPieces; i++) { if (this.pieceList[i] == null) { } else { data = Utils.concat(data, this.pieceList[i].data()); } } String saveAs = Constants.SAVEPATH; int offset = 0; if (this.nbOfFiles > 1) saveAs += this.torrent.saveAs + "/"; for (int i = 0; i < this.nbOfFiles; i++) { try { new File(saveAs).mkdirs(); FileOutputStream fos = new FileOutputStream(saveAs + ((String) (this.torrent.name.get(i)))); fos.write( Utils.subArray(data, offset, ((Integer) (this.torrent.length.get(i))).intValue())); fos.flush(); fos.close(); offset += ((Integer) (this.torrent.length.get(i))).intValue(); } catch (IOException ioe) { ioe.printStackTrace(); System.err.println( "Error when saving the file " + ((String) (this.torrent.name.get(i)))); } } } } }
private synchronized void save() { myDir.mkdirs(); Properties props = new Properties(); props.setProperty(KIND_KEY, myKind.toString()); props.setProperty(ID_KEY, myRepositoryId); props.setProperty(PATH_OR_URL_KEY, myRepositoryPathOrUrl); props.setProperty(INDEX_VERSION_KEY, CURRENT_VERSION); if (myUpdateTimestamp != null) props.setProperty(TIMESTAMP_KEY, String.valueOf(myUpdateTimestamp)); if (myDataDirName != null) props.setProperty(DATA_DIR_NAME_KEY, myDataDirName); if (myFailureMessage != null) props.setProperty(FAILURE_MESSAGE_KEY, myFailureMessage); try { FileOutputStream s = new FileOutputStream(new File(myDir, INDEX_INFO_FILE)); try { props.store(s, null); } finally { s.close(); } } catch (IOException e) { MavenLog.LOG.warn(e); } }
public void saveCache( JMXInstrumentedCache<K, V> cache, File savedCachePath, Function<K, byte[]> converter) throws IOException { long start = System.currentTimeMillis(); String msgSuffix = " " + savedCachePath.getName() + " for " + cfname + " of " + ksname; logger.debug("saving" + msgSuffix); int count = 0; File tmpFile = File.createTempFile(savedCachePath.getName(), null, savedCachePath.getParentFile()); FileOutputStream fout = new FileOutputStream(tmpFile); ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fout)); FileDescriptor fd = fout.getFD(); for (K key : cache.getKeySet()) { byte[] bytes = converter.apply(key); out.writeInt(bytes.length); out.write(bytes); ++count; } out.flush(); fd.sync(); out.close(); if (!tmpFile.renameTo(savedCachePath)) throw new IOException("Unable to rename cache to " + savedCachePath); if (logger.isDebugEnabled()) logger.debug( "saved " + count + " keys in " + (System.currentTimeMillis() - start) + " ms from" + msgSuffix); }
public static void saveObjectToFile(String fileName, Object obj) throws Exception { FileOutputStream ostream = new FileOutputStream(fileName); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeObject(obj); p.flush(); ostream.close(); }
public void get() throws Exception { byte[] b = new byte[8192]; int n = 0, t = 0; // t == total amount of downloaded bytes long length = smbFile.length(), initialTime, currentTime; float percentage; out = new FileOutputStream(downloadDir + "/" + smbFile.getName()); Date date = new Date(); initialTime = date.getTime(); while ((n = in.read(b)) > 0) { t += n; percentage = ((float) t / (float) length) * 100; currentTime = new Date().getTime(); float iets = (float) t; float tijd = (float) ((currentTime - initialTime) + 1); float speed = iets / tijd; System.out.printf("%3.2f %f KB/s\r", percentage, speed); System.out.flush(); out.write(b); } out.close(); System.out.println(); }
/** Saves the authorization database to disk. */ public void save() throws CoreException { if (!needsSaving || file == null) return; try { file.delete(); if ((!file.getParentFile().exists() && !file.getParentFile().mkdirs()) || !canWrite(file.getParentFile())) throw new CoreException( new Status( IStatus.ERROR, Platform.PI_RUNTIME, Platform.FAILED_WRITE_METADATA, NLS.bind(Messages.meta_unableToWriteAuthorization, file), null)); file.createNewFile(); FileOutputStream out = new FileOutputStream(file); try { save(out); } finally { out.close(); } } catch (IOException e) { throw new CoreException( new Status( IStatus.ERROR, Platform.PI_RUNTIME, Platform.FAILED_WRITE_METADATA, NLS.bind(Messages.meta_unableToWriteAuthorization, file), e)); } needsSaving = false; }
public synchronized void saveProperties() { if (ownLock()) { try { FileOutputStream out = new FileOutputStream(propertyFile); try { fontProps.store(out, "-- ICEpf Font properties --"); } finally { out.close(); } recordMofifTime(); } catch (IOException ex) { // check to make sure the storage relate dialogs can be shown if (getBoolean("application.showLocalStorageDialogs", true)) { Resources.showMessageDialog( null, JOptionPane.ERROR_MESSAGE, messageBundle, "fontManager.properties.title", "manager.properties.saveError", ex); } // log the error if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "Error saving font properties cache", ex); } } } }
void saveJar(File f, byte[] data) { try { FileOutputStream out = new FileOutputStream(f); out.write(data, 0, data.length); out.close(); } catch (IOException e) { } }
public static void writeURLtoFile(URL url, String filename) throws IOException { // FileWriter writer = new FileWriter(filename); // saveURL(url, writer); // writer.close(); FileOutputStream os = new FileOutputStream(filename); saveURL(url, os); os.close(); }
/** * This is a special version of the routine which knows the FileSystemProvider default format. * * @param dir * @param outFile * @throws IOException */ public static void exportWithDir(String dir, String outFile) throws IOException { FileOutputStream out = new FileOutputStream(new File(outFile)); Exporter x = new Exporter(out, true); x.export(dir); out.close(); }
public ParseDoc(Object xmlFile, String rootId, TreeMap prevIdMap) { SAXBuilder saxBuilder = new SAXBuilder(); try { if (xmlFile instanceof String) { document = saxBuilder.build((String) xmlFile); } else if (xmlFile instanceof URL) { document = saxBuilder.build((URL) xmlFile); } root = ParseUtils.parseRoot(document, rootId); objects = new TreeMap(); // Build description string (but not for the snippets.xml file) if (xmlFile instanceof String) { List authorL = root.getChildren("author"); String author = "<unknown>"; if (root.getAttributeValue("name") != null) { author = root.getAttributeValue("name"); } else if (authorL.size() > 0) { author = ((Element) authorL.get(0)).getValue(); } String description = "from file " + xmlFile.toString() + " (author: " + author + ") on " + new Date().toString(); HasIdentifiers.addGlobalIdentifier("_description_", description); } // Get all macro definitions, and remove them from document TreeMap macroMap = ParseUtils.getMacroDefs(root); // Process all macro expansions; replace macro expansion request with result ParseUtils.expandMacros(root, macroMap); // Get all elements in document, and assign identifiers to them; idMap = ParseUtils.parseId(root, prevIdMap); // Rewriting done; output debug XML code if (root.getAttributeValue("debug") != null) { XMLOutputter outputter = new XMLOutputter(); FileOutputStream fos = new FileOutputStream(xmlFile + ".debug"); outputter.output(document, fos); fos.close(); } } catch (JDOMException e) { // indicates a well-formedness or other error throw new Error("JDOMException: " + e.getMessage()); } catch (IOException e) { // indicates an IO problem throw new Error("IOException: " + e.getMessage()); } }
private void write(File f, byte[] bs) { try { FileOutputStream o = new FileOutputStream(f); o.write(bs, 0, bs.length); o.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * Crea el fichero de indices con la informacion inicial necesaria para un archivo concreto. * * @param fichero es el fichero de indices que tendra toda la informacion. * @param archivo es el objeto que representa el archivo en concreto. * @param fragmentos es la lista de fragmentos que faltan de dicho archivo. */ public void crearFicheroIndices(File fichero, Archivo archivo, Vector<Fragmento> fragmentos) { Vector<Fragmento> fragTengo = new Vector<Fragmento>(), fragFaltan = fragmentos; Indices indices = new Indices(archivo, fragTengo, fragFaltan); ByteArrayOutputStream bs = new ByteArrayOutputStream(); try { ObjectOutputStream os = new ObjectOutputStream(bs); os.writeObject(indices); os.close(); } catch (IOException e) { /*System.out.println("Error -> posibles causas: "); System.out.println( "\tProblemas al crear un flujo de bytes serializable" ); System.out.println( "\tProblemas al serializar el objeto indice" ); System.out.println( "\tProblemas al cerrar el flujo serializable" );*/ ControlDeErrores.getInstancia() .registrarError( ErrorEGorilla.ERROR_DISCO, "Error -> posibles causas: " + "\tProblemas al crear un flujo de bytes serializable" + "\tProblemas al serializar el objeto indice" + "\tProblemas al cerrar el flujo serializable"); // e.printStackTrace(); } byte[] bytes = bs.toByteArray(); // devuelve byte[] try { if (fichero.exists() == true) { String nombreNuevoFichero = fichero.getName(); nombreNuevoFichero += "_" + archivo.getHash(); fichero = new File(nombreNuevoFichero); } FileOutputStream ficheroIndices = new FileOutputStream(fichero); BufferedOutputStream bufferedOutput = new BufferedOutputStream(ficheroIndices); bufferedOutput.write(bytes, 0, bytes.length); bufferedOutput.close(); // creo que tambien hace falta cerrar el otro ficheroIndices.close(); } catch (FileNotFoundException e) { System.out.println("No existe el fichero <" + fichero.getName() + ">"); } catch (IOException e) { /*System.out.println("Error -> posibles causas: "); System.out.println( "\tProblemas al escribir en el fichero <"+fichero.getName()+">" ); System.out.println( "\tProblemas al cerrar el flujo o el fichero <"+fichero.getName()+">" );*/ ControlDeErrores.getInstancia() .registrarError( ErrorEGorilla.ERROR_DISCO, "Error -> posibles causas: " + "\tProblemas al escribir en el fichero <" + fichero.getName() + ">" + "\tProblemas al cerrar el flujo o el fichero <" + fichero.getName() + ">"); // e.printStackTrace(); } }
protected void saveGlyphFile(File a_file) throws FileNotFoundException { FileOutputStream output = new FileOutputStream(a_file); saveGlyphFile(output); try { output.close(); // JPEXS } catch (IOException ex) { Logger.getLogger(GlyphFile.class.getName()).log(Level.SEVERE, null, ex); } }
/** * @param args, arg[0] should be passed as the file path & name to be encrypted. * @throws Exception */ public static void main(String[] args) throws Exception { getBytes( args[ 0]); // calls get bytes method for converting file to bytes, need some way to remember // the file type. cipherText = doEncrypt(); FileOutputStream FOS = new FileOutputStream(new File("test.txt")); FOS.write(cipherText); // pri8nts the file of cipherText FOS.close(); }
/** Metodo que escreve os clientes num ficheiro */ public void escreveobjLocalidades(String fileLocalidades) throws FileNotFoundException, IOException { FileOutputStream fosloc = new FileOutputStream(fileLocalidades); ObjectOutputStream oosloc = new ObjectOutputStream(fosloc); oosloc.writeObject(this.localidades); oosloc.close(); fosloc.close(); }