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 String hash() throws NoSuchAlgorithmException, IOException { FileInputStream fis; MessageDigest md; String hex; StringBuffer hexString; byte[] dataBytes; int nread; md = MessageDigest.getInstance("MD5"); fis = new FileInputStream(this.path); dataBytes = new byte[65536]; hexString = new StringBuffer(); try { while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); } } finally { fis.close(); } byte[] mdbytes = md.digest(); for (int i = 0; i < mdbytes.length; i++) { hex = Integer.toHexString(0xff & mdbytes[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } fis.close(); return hexString.toString(); }
public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String f1, f2, f3; f1 = reader.readLine(); f2 = reader.readLine(); f3 = reader.readLine(); FileOutputStream file1 = new FileOutputStream(f1); FileInputStream file2 = new FileInputStream(f2); FileInputStream file3 = new FileInputStream(f3); byte buf[] = new byte[1000]; while (file2.available() > 0) { int count = file2.read(buf); file1.write(buf, 0, count); } while (file3.available() > 0) { int count = file3.read(buf); file1.write(buf, 0, count); } file1.close(); file2.close(); file3.close(); }
public static String readFile(String filename) { String s = ""; FileInputStream in = null; // FileReader in = null; try { File file = new File(filename); byte[] buffer = new byte[(int) file.length()]; // char[] buffer = new char[(int) file.length()]; in = new FileInputStream(file); // in = new FileReader(file); in.read(buffer); s = new String(buffer); in.close(); } catch (FileNotFoundException fnfx) { System.err.println("File not found: " + fnfx); } catch (IOException iox) { System.err.println("I/O problems: " + iox); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { // ignore } } } return s; }
public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String file1 = reader.readLine(); String file2 = reader.readLine(); FileInputStream inputStream1 = new FileInputStream(file1); FileInputStream inputStream2 = new FileInputStream(file2); ArrayList<Integer> list = new ArrayList<>(); while (inputStream2.available() > 0) { list.add(inputStream2.read()); } while (inputStream1.available() > 0) { list.add(inputStream1.read()); } FileOutputStream outputStream = new FileOutputStream(file1); for (Integer pair : list) { System.out.println(pair); outputStream.write(pair); } reader.close(); inputStream1.close(); inputStream2.close(); outputStream.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"); } }
public static void load(File dataFolder) throws IOException { FileInputStream playerClassesInput = new FileInputStream(dataFolder + "/data_pc"); playerClasses.load(playerClassesInput); playerClassesInput.close(); FileInputStream playerManaInput = new FileInputStream(dataFolder + "/data_pm"); playerMana.load(playerClassesInput); playerManaInput.close(); }
private boolean compareFiles(String filename1, String filename2) { FileInputStream f1, f2; int b1 = 0, b2 = 0; try { f1 = new FileInputStream(filename1); try { f2 = new FileInputStream(filename2); } catch (FileNotFoundException f2exc) { try { f1.close(); } catch (IOException exc) { } ; return false; // file 2 does not exist } } catch (FileNotFoundException f1exc) { return false; // file 1 does not exist } ; try { if (f1.available() != f2.available()) { return false; } // length of files is different while ((b1 != -1) & (b2 != -1)) { b1 = f1.read(); b2 = f2.read(); if (b1 != b2) { return false; } // discovered one diferring character } ; if ((b1 == -1) & (b2 == -1)) { return true; // reached both end of files } else { return false; // one end of file not reached } } catch (IOException exc) { return false; // read error, assume one file corrupted } finally { try { f1.close(); } catch (IOException exc) { } ; try { f2.close(); } catch (IOException exc) { } ; } }
/** * 根据文件以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; } }
/** * 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(); }
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(); } }
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!"); } }
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(); }
/** * @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 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 void openFile(String filename) { try { FileInputStream input = new FileInputStream(filename); char x; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { x = (char) input.read(); if (x == 'P') { puzzleBox[i][j].setText(String.valueOf((char) input.read())); puzzleBox[i][j].setEnabled(false); } else { x = (char) input.read(); if (x == 'X') { puzzleBox[i][j].setText(""); puzzleBox[i][j].setEnabled(true); } else { puzzleBox[i][j].setText(String.valueOf(x)); puzzleBox[i][j].setEnabled(true); } } } x = (char) input.read(); x = (char) input.read(); } input.close(); } catch (IOException ioException) { JOptionPane.showMessageDialog(this, "Error Opening File", "Error", JOptionPane.ERROR_MESSAGE); } }
/** * 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 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; }
@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(); }
/** * 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()); } } }
/** * 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(); } } }
/** * @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(); } }
// 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(); } }
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"; }
// post: input is closed public void close() { try { input.close(); } catch (IOException e) { throw new RuntimeException(e.toString()); } }
/** * 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; }