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 List<Supplier> GetSuppliers() { FileInputStream fis = null; ObjectInputStream ois = null; List<Supplier> suppliers = new ArrayList<Supplier>(); try { fis = new FileInputStream("Suppliers.dat"); ois = new ObjectInputStream(fis); while (true) { try { suppliers.add((Supplier) ois.readObject()); } catch (EOFException ex) { break; } } } catch (IOException ex) { System.out.println("Falha ao Ler arquivo de fornecedores!"); ex.getStackTrace(); } catch (ClassNotFoundException e) { System.out.println("Falha ao Ler arquivo de fornecedores!"); e.printStackTrace(); } finally { try { if (ois != null) ois.close(); if (fis != null) fis.close(); } catch (IOException ex) { System.out.println("Falha ao Ler arquivo de fornecedores!"); ex.getStackTrace(); } } return suppliers; }
public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
/** * @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(); } }
/** * 根据文件以byte[]形式返回文件的数据 * * @param file * @return */ public static byte[] getFileData(File file) { FileInputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(file); out = new ByteArrayOutputStream(BUFFER_SIZE); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ex) { ex.printStackTrace(); } } return out.toByteArray(); }
// Read up to 'len' bytes of Value. Value should already be persisted to // disk. A racing delete can trigger a failure where we get a null return, // but no crash (although one could argue that a racing load&delete is a bug // no matter what). @Override public byte[] load(Value v) { long skip = 0; Key k = v._key; // Convert an arraylet chunk into a long-offset from the base file. if (k._kb[0] == Key.ARRAYLET_CHUNK) { skip = ValueArray.getChunkOffset(k); // The offset k = ValueArray.getArrayKey(k); // From the base file key } if (k._kb[0] == Key.DVEC) { skip = water.fvec.NFSFileVec.chunkOffset(k); // The offset } try { FileInputStream s = null; try { s = new FileInputStream(getFileForKey(k)); FileChannel fc = s.getChannel(); fc.position(skip); AutoBuffer ab = new AutoBuffer(fc, true, Value.NFS); byte[] b = ab.getA1(v._max); ab.close(); assert v.isPersisted(); return b; } finally { if (s != null) s.close(); } } catch (IOException e) { // Broken disk / short-file??? H2O.ignore(e); return null; } }
public void run() { byte[] tmp = new byte[10000]; int read; try { FileInputStream fis = new FileInputStream(fileToSend.getFile()); read = fis.read(tmp); while (read != -1) { baos.write(tmp, 0, read); read = fis.read(tmp); System.out.println(read); } fis.close(); baos.writeTo(sWriter); sWriter.flush(); baos.flush(); baos.close(); System.out.println("fileSent"); } catch (IOException e) { e.printStackTrace(); } finally { this.closeSocket(); } }
/** * Zip up a directory path * * @param directory * @param zos * @param path * @throws IOException */ private static void zipDir(String directory, ZipOutputStream zos, String path) throws IOException { File zipDir = new File(directory); // get a listing of the directory content String[] dirList = zipDir.list(); byte[] readBuffer = new byte[2156]; int bytesIn = 0; // loop through dirList, and zip the files for (int i = 0; i < dirList.length; ++i) { File f = new File(zipDir, dirList[i]); if (f.isDirectory()) { zipDir(f.getPath(), zos, path.concat(f.getName()).concat(FILE_SEPARATOR)); continue; } FileInputStream fis = new FileInputStream(f); try { zos.putNextEntry(new ZipEntry(path.concat(f.getName()))); bytesIn = fis.read(readBuffer); while (bytesIn != -1) { zos.write(readBuffer, 0, bytesIn); bytesIn = fis.read(readBuffer); } } finally { closeQuietly(fis); } } }
/** * The read admin list reads in admin objects from a readfile * * @return * @throws FileNotFoundException */ public LinkedList<Admin> readAdminList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("adminList.csv"); LinkedList<Admin> adminList = new LinkedList<Admin>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates admin Admin newAdmin = new Admin(userName, password, email, firstName, lastName, office, phoneNumber); adminList.add(newAdmin); } fstream.close(); } catch (Exception e) { adminList = null; } Collections.sort(adminList); return adminList; }
/** * reads faculty list file * * @return LinkedList<Faculty> * @throws FileNotFoundException */ public LinkedList<Faculty> readFacultyList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("facultyList.csv"); LinkedList<Faculty> facultyList = new LinkedList<Faculty>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates faculty member Faculty newFaculty = new Faculty(userName, password, email, firstName, lastName, office, phoneNumber); facultyList.add(newFaculty); } fstream.close(); } catch (Exception e) { facultyList = null; } Collections.sort(facultyList); return facultyList; }
public static void readFile() { FileInputStream fis = null; try { // 创建流对象 fis = new FileInputStream("src/org/ucas/test/demo.txt"); // 读取数据到数组中 byte[] data = new byte[1204]; // 数据存储的数组 int i = 0; // 当前小标 // 读取流中的第一个字节数据 int n = fis.read(); // fis.read(data); // fis.read(data,1,2); // 依次读取后续的数据 while (n != -1) { data[i] = (byte) n; i++; n = fis.read(); // 读一个字节 } // 解析数据 String s = new String(data, 0, i); System.out.println(s); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { e.printStackTrace(); } } }
public ArrayList<FIncomePO> findAll() throws RemoteException { ArrayList<FIncomePO> incomeList = new ArrayList<FIncomePO>(); FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); FIncomePO in = (FIncomePO) ois.readObject(); while (fis.available() > 0) { byte[] buf = new byte[4]; fis.read(buf); FIncomePO incomepo = (FIncomePO) ois.readObject(); incomeList.add(incomepo); } } catch (Exception e) { e.printStackTrace(); } finally { try { ois.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } return incomeList; }
public ArrayList<FIncomePO> findByTime(String time1, String time2) throws RemoteException, IOException { ArrayList<FIncomePO> income = new ArrayList<FIncomePO>(); ObjectInputStream os = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); try { Date date1 = formatter.parse(time1); Date date2 = formatter.parse(time2); FileInputStream fs = new FileInputStream(file); os = new ObjectInputStream(fs); FIncomePO po = (FIncomePO) os.readObject(); while (fs.available() > 0) { byte[] buf = new byte[4]; fs.read(buf); FIncomePO incomepo = (FIncomePO) os.readObject(); if (formatter.parse(incomepo.getTime()).after(date1) && formatter.parse(incomepo.getTime()).before(date2)) { income.add(incomepo); } } return income; } catch (Exception e) { return null; } finally { os.close(); } }
public ArrayList<FIncomePO> findbyHall(String hall) throws RemoteException, IOException { ArrayList<FIncomePO> income = new ArrayList<FIncomePO>(); ObjectInputStream os = null; System.out.println("start find!"); try { FileInputStream fs = new FileInputStream(file); os = new ObjectInputStream(fs); FIncomePO po = (FIncomePO) os.readObject(); while (fs.available() > 0) { byte[] buf = new byte[4]; fs.read(buf); FIncomePO incomepo = (FIncomePO) os.readObject(); if (incomepo.getShop().equals(hall)) { income.add(incomepo); } } return income; } catch (Exception e) { return null; } finally { os.close(); } }
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 */ } } } }
/** * Copy a File * * @param fromFile The existing File * @param toFile The new File * @return <code>true</code> if and only if the renaming succeeded; <code>false</code> otherwise */ public static boolean copy(File fromFile, File toFile) { try { FileInputStream in = new FileInputStream(fromFile); FileOutputStream out = new FileOutputStream(toFile); byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) > -1) { out.write(buf, 0, len); } in.close(); out.close(); // cleanupif files are not the same length if (fromFile.length() != toFile.length()) { toFile.delete(); return false; } return true; } catch (IOException e) { e.printStackTrace(); return false; } }
public static FileInputStream resetInput(FileInputStream stream, File in, long toPoint) throws IOException { stream.close(); FileInputStream ret = new FileInputStream(in); ret.skip(toPoint); return ret; }
// find request file according to request.getUri() public void sendStaticResource() throws IOException { byte[] bytes = new byte[BUFFER_SIZE]; FileInputStream fis = null; try { File file = new File(HttpServer.WEB_ROOT, request.getUri()); if (file.exists()) { fis = new FileInputStream(file); int ch = fis.read(bytes, 0, BUFFER_SIZE); while (ch != -1) { output.write(bytes, 0, ch); ch = fis.read(bytes, 0, BUFFER_SIZE); } } else { String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + "\r\n" + "<h1>File Not Found</h1>"; output.write(errorMessage.getBytes()); } } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) fis.close(); } }
/** * @param startByte * @param endByte * @return * @throws Exception * @return true if all the bytes between in the file between startByte and endByte are null, false * otherwise */ private boolean isFilePortionNull(int startByte, int endByte) throws IOException { logger.config("Checking file portion:" + Hex.asHex(startByte) + ":" + Hex.asHex(endByte)); FileInputStream fis = null; FileChannel fc = null; try { fis = new FileInputStream(file); fc = fis.getChannel(); fc.position(startByte); ByteBuffer bb = ByteBuffer.allocateDirect(endByte - startByte); fc.read(bb); while (bb.hasRemaining()) { if (bb.get() != 0) { return false; } } } finally { if (fc != null) { fc.close(); } if (fis != null) { fis.close(); } } return true; }
public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("/Users/ksharma/dummy.txt"); out = new FileOutputStream("/Users/ksharma/out.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } catch (FileNotFoundException e) { System.out.println("file not found exception"); } catch (IOException e) { System.out.println("IO exception"); } finally { if (in != null) in.close(); if (out != null) out.close(); } CreateDir(); }
public String getFileBinaryBase64(String fileName) throws APIException { if ((new File(fileName)).exists()) { FileInputStream stream = null; try { stream = new FileInputStream(new File(fileName)); FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ byte[] b = new byte[bb.remaining()]; bb.get(b); return Base64.encodeBytes(b); } catch (Exception e) { throw new APIException(fileName + " could not have its files extracte!"); } finally { try { stream.close(); } catch (Exception e) { throw new APIException(fileName + " could not be closed!"); } } } else { throw new APIException(fileName + " doesn't exist!"); } }
/** * Method to copy a file from a source to a destination specifying if source files may overwrite * newer destination files and the last modified time of <code>destFile</code> file should be made * equal to the last modified time of <code>sourceFile</code>. * * @throws IOException */ public static void copyFile( File sourceFile, File destFile, boolean overwrite, boolean preserveLastModified) throws IOException { if (overwrite || !destFile.exists() || destFile.lastModified() < sourceFile.lastModified()) { if (destFile.exists() && destFile.isFile()) { destFile.delete(); } // ensure that parent dir of dest file exists! // not using getParentFile method to stay 1.1 compat File parent = new File(destFile.getParent()); if (!parent.exists()) { parent.mkdirs(); } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.close(); out.close(); if (preserveLastModified) { destFile.setLastModified(sourceFile.lastModified()); } } }
/** * Reload properties. This clears out the existing entries, loads the main properties file and * then adds any additional properties there may be (usually from zip files). This is used * internally by addProps() and removeProps(). */ private synchronized void reload() { // clear out old entries clear(); // read from the primary file if (file != null && file.exists()) { FileInputStream bpin = null; try { bpin = new FileInputStream(file); load(bpin); } catch (Exception x) { System.err.println("Error reading properties from file " + file + ": " + x); } finally { try { bpin.close(); } catch (Exception ignore) { // ignored } } } // read additional properties from zip files, if available if (additionalProps != null) { for (Iterator i = additionalProps.values().iterator(); i.hasNext(); ) putAll((Properties) i.next()); } lastread = System.currentTimeMillis(); }
@Test @Category(UnitTest.class) public void readSplits() throws IOException { File splitfile = folder.newFile(testName.getMethodName()); FileOutputStream stream = new FileOutputStream(splitfile); PrintWriter writer = new PrintWriter(stream); writer.println(generated.length); for (int i = 0; i < generated.length; i++) { writer.print(generated[i]); writer.print(" "); writer.println(i); } writer.close(); stream.close(); FileInputStream in = new FileInputStream(splitfile); Splits splits = new PartitionerSplit(); splits.readSplits(in); PartitionerSplit.PartitionerSplitInfo[] si = (PartitionerSplit.PartitionerSplitInfo[]) splits.getSplits(); Assert.assertEquals("Splits length not correct", generated.length, si.length); for (int i = 0; i < generated.length; i++) { Assert.assertEquals("Splits entry not correct", generated[i].longValue(), si[i].getTileId()); } in.close(); }
public static void main(String args[]) throws Exception { // 参数 String cacert = args[0]; String lfcert = args[1]; // CA "Xu Yingxiao"的证书 CertificateFactory cf = CertificateFactory.getInstance("X.509"); FileInputStream in1 = new FileInputStream(cacert); java.security.cert.Certificate cac = cf.generateCertificate(in1); in1.close(); // 用户"Liu Fang"的签名证书 FileInputStream in2 = new FileInputStream(lfcert); java.security.cert.Certificate lfc = cf.generateCertificate(in2); in2.close(); PublicKey pbk = cac.getPublicKey(); boolean pass = false; try { lfc.verify(pbk); pass = true; } catch (Exception e) { pass = false; System.out.println(e); } if (pass) { System.out.println("The Certificate is signed by the CA Xu Yingxiao"); } else { System.out.println("!!!The Certificate is not signed by the CA Xu Yingxiao"); } }
/** * Loads configuration parameters from the file with the given name. Sets private variable to the * loaded values. */ public static void loadProperties(String fileName) throws IOException { System.out.println("Reading configuration file " + fileName + "..."); FileInputStream propsFile = new FileInputStream(fileName); properties.load(propsFile); propsFile.close(); System.out.println("Setting default parameters..."); FTP_SERVER = properties.getProperty("FTP_SERVER"); FTP_USER = properties.getProperty("FTP_USER"); FTP_PASSWORD = properties.getProperty("FTP_PASSWORD"); FTP_PATH = properties.getProperty("FTP_PATH"); LOCAL_FOLDER = properties.getProperty("LOCAL_FOLDER"); SENT_FOLDER = properties.getProperty("SENT_FOLDER"); FILE_EXTENSION = properties.getProperty("FILE_EXTENSION"); IS_8X = properties.getProperty("IS_8X", IS_8X); LIMIT_RECORD = properties.getProperty("LIMIT_RECORD"); MOBILE_OPERATOR = properties.getProperty("MOBILE_OPERATOR", MOBILE_OPERATOR); int time = getIntProperty("SCHEDULE_TIME", SCHEDULE_TIME); // if (time < 1) { // time = 1; // } // if (time > 20) { // time = 20; // } SCHEDULE_TIME = time; }
public static void copyFile(File sourceFile, File destinationFile) { try { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; // Inner try block is for streams and readers that needs closing. try { fileInputStream = new FileInputStream(sourceFile); fileOutputStream = new FileOutputStream(destinationFile); byte[] buffer = new byte[1024]; int length = 0; while ((length = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, length); } } finally { if (fileInputStream != null) fileInputStream.close(); if (fileOutputStream != null) fileOutputStream.close(); } } catch (Throwable throwable) { App.e(FileUtilities.class, throwable); } }
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; }
public static PropertiesManager getInstance() { if (instance == null) { instance = new PropertiesManager(); props = new Properties(); // make sure something was passed in. If no, set to defaults try { String fileName = System.getProperty("SUT"); if ((fileName == null) || (fileName.equals(""))) { fileName = "CI"; } // load the properties into memory FileInputStream in = new FileInputStream(propertiesFilePath + fileName + ".properties"); props.load(in); in.close(); } catch (IOException e) { e.printStackTrace(); } // Dump the properties on debug for (String key : props.stringPropertyNames()) { // System.out.println("Property " + key + " = " + props.getProperty(key)); } } return instance; }
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); }