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()); } } }
public static FileDesc loadFile(Path root, Path file, int blocSize) throws NoSuchAlgorithmException, FileNotFoundException, IOException { MessageDigest md = MessageDigest.getInstance("SHA-512"); MessageDigest fileMd = MessageDigest.getInstance("SHA-512"); FileDesc desc = new FileDesc(file.toString(), null, null); List<Bloc> list = new ArrayList<Bloc>(); try (FileInputStream fis = new FileInputStream(root.resolve(file).toString())) { byte[] buf = new byte[blocSize]; byte[] h; int s; while ((s = fis.read(buf)) != -1) { int c; while (s < buf.length && (c = fis.read()) != -1) buf[s++] = (byte) c; fileMd.update(buf, 0, s); // padding byte p = 0; while (s < buf.length) buf[s++] = ++p; h = md.digest(buf); Bloc bloc = new Bloc(RollingChecksum.compute(buf), new Hash(h)); list.add(bloc); } h = fileMd.digest(); desc.fileHash = new Hash(h); desc.blocs = list.toArray(new Bloc[0]); } return desc; }
/** * Reads a line from the file. * * @return Line readed. */ public String readLine() throws Exception { char c; String a = ""; c = (char) fileInput.read(); do { a = a + c; c = (char) fileInput.read(); } while ((fileInput.available() != 0) && (c != '\n')); if (c != ' ') { a = a + c; } return a; }
// pre : given file name is legal // post: creates a BitInputStream reading input from the file public BitInputStream(String file) { try { input = new FileInputStream(file); // Read in the number of remaining bits at the end this.remainingAtEnd = input.read(); // Set up the nextByte field. this.nextByte = input.read(); } catch (IOException e) { throw new RuntimeException(e.toString()); } this.nextByte(); }
/** * 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")); } }
public static void main(String args[]) { try { aServer asr = new aServer(); // file channel. FileInputStream is = new FileInputStream(""); is.read(); FileChannel cha = is.getChannel(); ByteBuffer bf = ByteBuffer.allocate(1024); bf.flip(); cha.read(bf); // Path Paths Path pth = Paths.get("", ""); // Files some static operation. Files.newByteChannel(pth); Files.copy(pth, pth); // file attribute, other different class for dos and posix system. BasicFileAttributes bas = Files.readAttributes(pth, BasicFileAttributes.class); bas.size(); } catch (Exception e) { System.err.println(e); } System.out.println("hello "); }
public void load() { if (!modelExists()) { loadError = "Cannot find " + LEVELS_DAT_FILE + "."; return; } File folder = new File(location); File dat = new File(folder, LEVELS_DAT_FILE); // File lst = new File(folder, LEVELS_LST_FILE); if (!dat.isFile()) return; ArrayList levels = new ArrayList(); try { FileInputStream reader = new FileInputStream(dat); long fileLength = dat.length(); int length = model.getField().getSize() + 96; int readLength = 0; byte[] buffer = new byte[length]; while (fileLength - readLength >= length) { int toRead = length; while (toRead > 0) { toRead -= reader.read(buffer, length - toRead, toRead); } readLength += length; SupaplexLevel level = new SupaplexLevel(); level.setModel(model); level.loadFromBytes(buffer); levels.add(level); } reader.close(); } catch (Exception e) { e.printStackTrace(); } SupaplexLevel[] ls = (SupaplexLevel[]) levels.toArray(new SupaplexLevel[0]); model.setLevels(ls); }
/** * @ensures: if input file is read, a String is filled with words from file and searched in * dictionary list, and if found increase words found counter, otherwise increase words not * found. Otherwise error reading file */ public void readFileOliver() { try { FileInputStream inf = new FileInputStream(new File("oliver.txt")); char let; String str = ""; String key = ""; int n = 0; while ((n = inf.read()) != -1) { let = (char) n; if (Character.isLetter(let)) { str += Character.toLowerCase(let); } if ((Character.isWhitespace(let) || let == '-') && !str.isEmpty()) { key = str; str = ""; boolean a = dictionary[(int) key.charAt(0) - 97].contains(key); if (a == true) { counter = dictionary[(int) key.charAt(0) - 97].indexOf(key); counterWFound++; counterWFCompared += counter; } else { counter = dictionary[(int) key.charAt(0) - 97].indexOf( dictionary[(int) key.charAt(0) - 97].getLast()); counterWNotFound++; counterWNFCompared += counter; } } } inf.close(); } catch (IOException e) { e.printStackTrace(); } }
private Parser readContent() { Parser infoParser; String filename = FILE_READ_PATH + FILE_READ_BASE_NAME + "." + FILE_READ_EXT_NUM; FILE_READ_EXT_NUM++; try { File file = new File(filename); if (DEBUG) displayMessage( "DEBUG", "WCNForecastWeatherQueryFn.readContent:: File " + filename + " file.length=" + file.length()); byte bytes[] = new byte[(int) (file.length())]; FileInputStream fis = new FileInputStream(file); int cnt = fis.read(bytes, 0, bytes.length); if (DEBUG) displayMessage( "DEBUG", "WCNForecastWeatherQueryFn.readContent:: File " + filename + " read cnt=" + cnt); fis.close(); if (cnt != bytes.length) return null; String content = new String(bytes); infoParser = new Parser(content, true, display); } catch (FileNotFoundException e) { if (DEBUG) displayMessage("ERROR", "File " + filename + " not found."); return null; } catch (IOException e) { if (DEBUG) displayMessage("ERROR", "Read failed on file " + filename); return null; } return infoParser; }
// 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; } }
private byte[] loadClassData(File f) throws ClassNotFoundException { FileInputStream stream = null; try { // System.out.println("loading: "+f.getPath()); stream = new FileInputStream(f); try { byte[] b = new byte[stream.available()]; stream.read(b); return b; } catch (IOException e) { throw new ClassNotFoundException(); } } catch (FileNotFoundException e) { throw new ClassNotFoundException(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { /* ignore */ } } } }
/** * Load text string from a given file. * * @param fileStr the name of the file to be loaded. * @return A text string that is the content of the file. if the given file is not exist, then * return null. */ public static String getStringFromFile(String fileStr) throws Exception { String getStr = null; FileInputStream pspInputStream = new FileInputStream(fileStr); byte[] pspFileBuffer = new byte[pspInputStream.available()]; pspInputStream.read(pspFileBuffer); pspInputStream.close(); getStr = new String(pspFileBuffer); return (getStr); }
private void sendBytes(FileInputStream fis) throws Exception { // Construct a 1K buffer to hold bytes on their way to the socket. byte[] buffer = new byte[1024]; int bytes = 0; while ((bytes = fis.read(buffer)) != -1) { sockManager.Escribir(buffer, bytes); } }
public static void copyFileToTheStandardOutput(String inputFileName) throws IOException { FileInputStream fis = new FileInputStream(inputFileName); int c; while ((c = fis.read()) != -1) { System.out.write(c); // won't work with big files as something // can write on the screen in the middle of the reading } fis.close(); }
public static Charset guessEncoding(File f, int bufferLength, Charset defaultCharset) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(f); byte[] buffer = new byte[bufferLength]; fis.read(buffer); fis.close(); CharsetToolkit toolkit = new CharsetToolkit(buffer); toolkit.setDefaultCharset(defaultCharset); return toolkit.guessEncoding(); }
public static void main(String[] args) { byte[] T, U, V; int[] A; int i, j, n, pidx; long start, finish; for (i = 0; i < args.length; ++i) { System.out.print(args[i] + ": "); try { /* Open a file for reading. */ File f = new File(args[i]); FileInputStream s = new FileInputStream(f); n = (int) f.length(); System.out.print(n + " bytes ... "); /* Allocate 5n bytes of memory. */ T = new byte[n]; U = new byte[n]; V = new byte[n]; A = new int[n]; /* Read n bytes of data. */ s.read(T); s.close(); s = null; f = null; /* Construct the suffix array. */ start = new Date().getTime(); pidx = new sais().bwtransform(T, U, A, n); finish = new Date().getTime(); System.out.println(((finish - start) / 1000.0) + " sec"); System.out.print("unbwtcheck ... "); unbwt(U, V, A, n, pidx); for (j = 0; j < n; ++j) { if (T[j] != V[j]) { System.err.println("error " + j + ": " + T[j] + ", " + V[j]); return; } } System.err.println("Done."); T = null; U = null; V = null; A = null; } catch (IOException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } } }
/** * @param guid * @return * @throws IOException */ public byte[] read(int guid) throws IOException { // read from file, return contents File file = new File(Integer.toString(guid)); FileInputStream fis = null; fis = new FileInputStream(file); byte[] data = new byte[fis.available()]; fis.read(data); return data; }
Decompressor(String inFile) throws Exception { lastString = ""; finish = false; cursor = 0; output = new Vector(); FileInputStream inStream = new FileInputStream(inFile); FileWriter fw = new FileWriter(inFile + "." + DECOMPRESSED_FILE_EXTENSION); oWriter = fw; while (true) { int indexHigh = (byte) inStream.read(); if (indexHigh == -1) break; int indexMiddle = (byte) inStream.read(); int indexLow = (byte) inStream.read(); int index = indexHigh * BLOCK_SIZE * BLOCK_SIZE + indexMiddle * BLOCK_SIZE + indexLow; char c = (char) inStream.read(); output.add(new Pair(index, c)); } }
public static byte[] getBytes(File file) throws IOException { if (file == null || !file.exists()) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); FileInputStream in = new FileInputStream(file); int c = in.read(); while (c != -1) { out.write(c); c = in.read(); } in.close(); out.close(); return out.toByteArray(); }
private void sendData(FileInputStream data) throws SerialConnectionException { int tosend = 0; byte[] databuff = new byte[_chunkSize]; _sent = 0; try { tosend = data.read(databuff); while (tosend != -1) { if (!_keepRunning) return; _os.write(databuff, 0, tosend); _savedStream.write(databuff, 0, tosend); _sent += tosend; // update GUI _results.updateBytesSent(_sent); tosend = data.read(databuff); } } catch (IOException e) { throw new SerialConnectionException("Error writing to i/o streams"); } }
public Level1State read() { try { data = new byte[(int) file.length()]; FileInputStream in = new FileInputStream(file); in.read(data); in.close(); } catch (Exception e) { e.printStackTrace(); } Level1State l1s = Level1State.deserialize(data); return l1s; }
private void file_to_file(File in_file, File out_file) throws IOException, InterruptedException { FileInputStream in = in_file.inputStream(); FileOutputStream out = out_file.outputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int n_read; while ((n_read = in.read(buffer)) != -1) { checkForInterruption(); out.write(buffer, 0, n_read); } in.close(); out.close(); }
// post: refreshes the internal buffer with the next BYTE_SIZE bits private void nextByte() { this.currentByte = this.nextByte; if (this.currentByte != -1) { try { this.nextByte = input.read(); } catch (IOException e) { throw new RuntimeException(e.toString()); } } this.numBits = 0; }
public static void main(String[] args) throws Exception { ByteArrayOutputStream bout; ByteArrayInputStream bin; ObjectOutputStream oout; ObjectInputStream oin; FileInputStream fin; File foof; CustomOutputStream cout; CustomInputStream cin; // test for backwards compatibility bout = new ByteArrayOutputStream(); foof = new File(System.getProperty("test.src", "."), "Foo.ser"); fin = new FileInputStream(foof); while (fin.available() > 0) bout.write(fin.read()); byte[] buf1 = bout.toByteArray(); bout = new ByteArrayOutputStream(); oout = new ObjectOutputStream(bout); Foo foo = new Foo(); oout.writeObject(foo); oout.flush(); byte[] buf2 = bout.toByteArray(); if (!Arrays.equals(buf1, buf2)) throw new Error("Incompatible stream format (write)"); fin = new FileInputStream(foof); oin = new ObjectInputStream(fin); Foo foocopy = (Foo) oin.readObject(); if (!foo.equals(foocopy)) throw new Error("Incompatible stream format (read)"); // make sure write hook not called when old protocol in use bout = new ByteArrayOutputStream(); cout = new CustomOutputStream(bout); cout.useProtocolVersion(PROTOCOL_VERSION_1); cout.writeObject(foo); if (cout.hookCalled) throw new Error("write descriptor hook should not be called"); // write custom class descriptor representations bout = new ByteArrayOutputStream(); cout = new CustomOutputStream(bout); cout.writeObject(foo); cout.flush(); bin = new ByteArrayInputStream(bout.toByteArray()); cin = new CustomInputStream(bin); foocopy = (Foo) cin.readObject(); if (!cout.hookCalled) throw new Error("write descriptor hook never called"); if (!cin.hookCalled) throw new Error("read descriptor hook never called"); if (!foo.equals(foocopy)) throw new Error("serialization failed when hooks active"); }
/** Procedure to set value for the code-swap strings */ void getCodeSwapString() { File inputFile = new File(fileStr1); FileInputStream input = null; try { input = new FileInputStream(inputFile); } catch (FileNotFoundException fe) { System.err.println(fileStr1 + " not found. " + fe); // System.exit(-1);; } byte bt[] = new byte[(int) inputFile.length()]; try { input.read(bt); textStr1 = new String(bt); input.close(); } catch (IOException ie) { System.err.println("Can't read from the input stream " + ie); // System.exit(-1);; } inputFile = new File(fileStr2); try { input = new FileInputStream(inputFile); } catch (FileNotFoundException fe) { System.err.println(fileStr2 + " not found. " + fe); // System.exit(-1);; } try { bt = new byte[(int) inputFile.length()]; input.read(bt); textStr2 = new String(bt); input.close(); } catch (IOException ie) { System.err.println("Can't read from the input stream " + ie); // System.exit(-1);; } }
public char[] getCharacters() throws Exception { char[] ret = new char[(int) (inFile.length() + 1)]; int retCursor = 0; FileInputStream from = new FileInputStream(inFile); while (true) { byte nextByte = (byte) from.read(); if (nextByte == -1) break; char nextChar = (char) nextByte; ret[retCursor++] = nextChar; } ret[(int) (inFile.length())] = '\000'; return ret; }
// Choose between wbxml or zip (the smallest one) to be used; // adds 3 additional bytes with metadata and set binary data for the record // returns length for the application settings + 3 bytes public int setBlockApplicationsForOneRecord(Record record) throws Exception { String key = record.key; // String generalPath = Const.WORKING_DIR + Const.PATH_SEP + // key.replaceAll(":", "_"); String generalPath = Const.WORKING_DIR + Const.PATH_SEP + Util.generateFileNameFromKey(key); File w = new File(generalPath + ".wbxml"); if (!w.exists()) { throw new Exception("Error: The file " + generalPath + ".wbxml doesn't exist!"); } FileInputStream in; boolean usedZip; // Choose between wbxml or zip (the smallest one) to be used in case if USE_ZIP // has not been set to false in function main(). if (USE_ZIP) { // zip wbxml files File z = new File(generalPath + ".zip"); if (!z.exists()) { throw new Exception("Error: The file " + generalPath + ".zip doesn't exist!"); } FileInputStream inw = new FileInputStream(w); FileInputStream inz = new FileInputStream(z); usedZip = inz.available() < inw.available(); in = (usedZip) ? inz : inw; } else { // do not zip wbxml files usedZip = false; in = new FileInputStream(w); } byte[] appWbxmlSettings = new byte[in.available()]; in.read(appWbxmlSettings); in.close(); // get 3 bytes that provide info: for data length (23 bits) and compressed flag (1 bit) // and write it into metaInfo BlockTable metaInfo = new BlockTable((Const.APP_BLOCK_LENGTH + Const.APP_COMPRESSWD_FLAG) / 8); // 3 bytes int appBlockSettingsLength = metaInfo.data.length + appWbxmlSettings.length; int compressFlag = (usedZip) ? 1 : 0; Util.addBitsToTable(metaInfo, appBlockSettingsLength, Const.APP_BLOCK_LENGTH); Util.addBitsToTable(metaInfo, compressFlag, Const.APP_COMPRESSWD_FLAG); record.setBlockApplicationSettings(metaInfo.data, appWbxmlSettings); Validator.validateAppBlockSettingsLength(appBlockSettingsLength, generalPath); return appBlockSettingsLength; }
public Class loadNewClass(String javaFile, String packageName) { Class myClass = null; String className = javaFile.replace(".java", ".class"); File inpFile = new File(className); int idx = className.lastIndexOf(File.separatorChar); String javaName = className.substring(idx + 1, className.indexOf(".")); int size = (int) inpFile.length(); byte[] ba = new byte[size]; try { FileInputStream fis = new FileInputStream(className); // read the entry int bytes_read = 0; while (bytes_read != size) { int r = fis.read(ba, bytes_read, size - bytes_read); if (r < 0) break; bytes_read += r; } if (bytes_read != size) throw new IOException("cannot read entry"); } catch (FileNotFoundException fnfExc) { System.out.println("File : " + className + " not found"); fnfExc.printStackTrace(); } catch (IOException ioExc) { System.out.println("IO Exception in JavaCompile trying to read class: "); ioExc.printStackTrace(); } try { String packageAppendedFileName = ""; if (packageName.isEmpty()) packageAppendedFileName = javaName; else packageAppendedFileName = packageName + "." + javaName; packageAppendedFileName.replace(File.separatorChar, '.'); myClass = defineClass(packageAppendedFileName, ba, 0, size); // SOS-StergAutoCompletionScalaSci.upDateAutoCompletion(myClass); String userClassName = myClass.getName(); JOptionPane.showMessageDialog(null, "Class " + userClassName + " loaded successfully !"); } catch (ClassFormatError exc) { System.out.println("error defining class " + inpFile); exc.printStackTrace(); } catch (Exception ex) { System.out.println("some error defining class " + inpFile); ex.printStackTrace(); } return myClass; }
protected byte[] getClassData(String directory, String name) { String classFile = directory + "/" + name.replace('.', '/') + ".class"; int classSize = (int) new File(classFile).length(); byte[] buf = new byte[classSize]; try { FileInputStream filein = new FileInputStream(classFile); classSize = filein.read(buf); filein.close(); } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } return buf; }
/** * Copy source file to destination file. * * @throws SecurityException * @throws IOException */ public static void copyFile(File destfile, File srcfile) throws IOException { byte[] bytearr = new byte[512]; int len = 0; FileInputStream input = new FileInputStream(srcfile); File destDir = destfile.getParentFile(); destDir.mkdirs(); FileOutputStream output = new FileOutputStream(destfile); try { while ((len = input.read(bytearr)) != -1) { output.write(bytearr, 0, len); } } catch (FileNotFoundException exc) { } catch (SecurityException exc) { } finally { input.close(); output.close(); } }