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 StringBuffer CheckSum(String source) throws NoSuchAlgorithmException, IOException { // MessageDigest md = MessageDigest.getInstance("MD5"); // Change MD5 to SHA1 to get SHA checksum MessageDigest md = MessageDigest.getInstance("SHA1"); FileInputStream fis = new FileInputStream(source); byte[] dataBytes = new byte[4096]; int nread = 0; while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); } ; byte[] mdbytes = md.digest(); // convert the byte to hex format StringBuffer sb = new StringBuffer(""); for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } // System.out.println("Checksum"); // System.out.println(sb.toString() + " " + source); // System.out.println("------------------"); fis.close(); return sb; }
public Bitmap getBitmapFromSd(String imgFilePath) { FileInputStream fis = null; try { fis = new FileInputStream(new File(imgFilePath)); // 文件输入流 Bitmap bmp = BitmapFactory.decodeStream(fis); return bmp; } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; }
public void kopi(String sumber, String sasaran) throws IOException { FileInputStream masukan = null; FileOutputStream keluaran = null; BufferedInputStream masukanBuffer = null; BufferedOutputStream keluaranBuffer = null; try { masukan = new FileInputStream(sumber); masukanBuffer = new BufferedInputStream(masukan); keluaran = new FileOutputStream(sasaran); keluaranBuffer = new BufferedOutputStream(keluaran); int karakter = masukanBuffer.read(); while (karakter != -1) { keluaranBuffer.write(karakter); karakter = masukanBuffer.read(); } keluaranBuffer.flush(); } finally { if (masukan != null) masukan.close(); if (masukanBuffer != null) masukanBuffer.close(); if (keluaran != null) keluaran.close(); if (keluaranBuffer != null) { keluaranBuffer.close(); } } }
public String badSource(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; if (CWE601_Open_Redirect__Servlet_PropertiesFile_22a.badPublicStatic) { data = ""; /* Initialize data */ /* retrieve the property */ { Properties properties = new Properties(); FileInputStream streamFileInput = null; try { streamFileInput = new FileInputStream("../common/config.properties"); properties.load(streamFileInput); /* POTENTIAL FLAW: Read data from a .properties file */ data = properties.getProperty("data"); } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading object */ try { if (streamFileInput != null) { streamFileInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } return data; }
public void run(String[] args) { String script = null; try { FileInputStream stream = new FileInputStream(new File(args[0])); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); script = Charset.availableCharsets().get("UTF-8").decode(bb).toString(); } finally { stream.close(); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } Context cx = Context.enter(); try { ScriptableObject scope = cx.initStandardObjects(); scope.putConst("language", scope, "java"); scope.putConst("platform", scope, "android"); scope.put("util", scope, new Util(cx, scope)); cx.evaluateString(scope, script, args[0], 1, null); } catch (Error ex) { ex.printStackTrace(); System.exit(1); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } finally { Context.exit(); } System.exit(0); }
public static void loadTile(TileProvider provider, Tile t) { BaseApplication application = BaseApplication.getApplication(); if (application == null) return; File cache = application.getCacheDir(); if (cache == null) // cache is not available now return; File file = getTileFile(cache, provider.code, t.x, t.y, t.zoomLevel); if (!file.exists()) return; try { FileInputStream fileInputStream; fileInputStream = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; int count = fileInputStream.read(data); fileInputStream.close(); if (count != data.length) return; t.bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); t.expired = provider.tileExpiration > 0 && file.lastModified() + provider.tileExpiration < System.currentTimeMillis(); } catch (IOException e) { e.printStackTrace(); } }
// decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) { try { // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream stream1 = new FileInputStream(f); BitmapFactory.decodeStream(stream1, null, o); stream1.close(); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 70; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; FileInputStream stream2 = new FileInputStream(f); Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2); stream2.close(); return bitmap; } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } return null; }
/** * Starts this sample with the data that is read from the file with the given name. The data is * assumed to have the specified dimensions. * * @param fileName The name of the volume data file to load * @param sizeX The size of the data set in X direction * @param sizeY The size of the data set in Y direction * @param sizeZ The size of the data set in Z direction * @param stereoMode Whether stereo mode should be used */ private static void startSample( String fileName, final int sizeX, final int sizeY, final int sizeZ, final boolean stereoMode) { // Try to read the specified file byte data[] = null; try { int size = sizeX * sizeY * sizeZ; FileInputStream fis = new FileInputStream(fileName); data = new byte[size]; fis.read(data); fis.close(); } catch (IOException e) { System.err.println("Could not load input file"); e.printStackTrace(); return; } // Start the sample with the data that was read from the file final byte volumeData[] = data; SwingUtilities.invokeLater( new Runnable() { public void run() { new OpenCLVolumeRenderer(volumeData, sizeX, sizeY, sizeZ, stereoMode); } }); }
@Override public void reloadProperties() throws Exception { File dir = Environment.getDefault().getConfig(); String[] names = dir.list(); if (names != null) { Arrays.sort( names, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); Properties props = new Properties(); for (String name : names) { if (name.endsWith(".config") || name.endsWith(".ini") || name.endsWith(".properties")) { FileInputStream in = new FileInputStream(new File(dir, name)); try { props.load(in); } finally { in.close(); } } } // replace the current runtime properties properties = props; } }
public void loadWorld(String filename) { try { File f = new File(filename); byte[] data = null; if (!f.exists()) { System.out.println(filename + ": Level not found."); generate(); return; } else { try { FileInputStream fis = new FileInputStream(f); data = new byte[fis.available()]; fis.read(data); } catch (Exception e) { e.printStackTrace(); } } Tile tile = null; int i = 0; for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { tile = new Tile(x, y, 0, false, false, false); if (data[i] == 1) tile = new Brick(x, y); else if (data[i] == 2) tile = new Stone(x, y); else if (data[i] == 3) tile = new Leaf(x, y); else if (data[i] == 4) tile = new Water(x, y); tiles[x][y] = tile; i++; } } } catch (Exception e) { gc.city.Crash(e); } }
public boolean createJar(File jarFilename, File... filesToAdd) { try { FileOutputStream stream = new FileOutputStream(jarFilename); JarOutputStream out = new JarOutputStream(stream, new Manifest()); BufferedOutputStream bos = new BufferedOutputStream(out); for (File fileToAdd : filesToAdd) { if (fileToAdd == null || !fileToAdd.exists() || fileToAdd.isDirectory()) { continue; // Just in case... } JarEntry jarAdd = new JarEntry(fileToAdd.getName()); jarAdd.setTime(fileToAdd.lastModified()); out.putNextEntry(jarAdd); FileInputStream in = new FileInputStream(fileToAdd); BufferedInputStream bis = new BufferedInputStream(in); int data; while ((data = bis.read()) != -1) { bos.write(data); } bis.close(); in.close(); } bos.close(); out.close(); stream.close(); } catch (FileNotFoundException e) { // skip not found file } catch (IOException e) { e.printStackTrace(); } return true; }
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"; }
private static Drawable loadDrawableFromStream( Context context, String url, String filename, int targetWidth, int targetHeight) { prepareResources(context); // Log.v(Constants.LOGTAG,targetWidth); // Log.v(Constants.LOGTAG,targetHeight); try { Options o = new Options(); o.inJustDecodeBounds = true; FileInputStream stream = new FileInputStream(filename); BitmapFactory.decodeStream(stream, null, o); stream.close(); stream = new FileInputStream(filename); int scale = 0; while ((o.outWidth >> scale) > targetWidth || (o.outHeight >> scale) > targetHeight) { Log.v(Constants.LOGTAG, "downsampling"); scale++; } o = new Options(); o.inSampleSize = 1 << scale; Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o); if (Constants.LOG_ENABLED) Log.i( Constants.LOGTAG, String.format("Loaded bitmap (%dx%d).", bitmap.getWidth(), bitmap.getHeight())); BitmapDrawable bd = new BitmapDrawable(mResources, bitmap); return new ZombieDrawable(url, bd); } catch (IOException e) { return null; } }
@Override public void createDestination() throws Exception { FileInputStream schemaIn = new FileInputStream(avsc); Schema original = new Schema.Parser().parse(schemaIn); schemaIn.close(); Schema evolved = getEvolvedSchema(original); FileOutputStream schemaOut = new FileOutputStream(evolvedAvsc); schemaOut.write(evolved.toString(true).getBytes()); schemaOut.close(); List<String> createArgs = Lists.newArrayList("create", dest, "-s", evolvedAvsc, "-r", repoUri, "-d", "target/data"); createArgs.addAll(getExtraCreateArgs()); TestUtil.run( LoggerFactory.getLogger(this.getClass()), "delete", dest, "-r", repoUri, "-d", "target/data"); TestUtil.run( LoggerFactory.getLogger(this.getClass()), createArgs.toArray(new String[createArgs.size()])); this.console = mock(Logger.class); this.command = new CopyCommand(console); command.setConf(new Configuration()); }
public boolean exist(String identifiant) { boolean exist = false; File file = new File(fileName); FileInputStream fileInput = null; try { fileInput = new FileInputStream(file); Properties prop = new Properties(); // load a properties file from class path, inside static method prop.load(fileInput); if (prop.getProperty(identifiant) != null) { // Client déja présent exist = true; } } catch (IOException ex) { ex.printStackTrace(); } finally { if (fileInput != null) { try { fileInput.close(); } catch (IOException e) { e.printStackTrace(); } } } return exist; }
@Before public void setUp() throws Exception { // Download file for test URL website = new URL("http://archive.org/web/images/logo_wayback_210x77.png"); ReadableByteChannel resFile = Channels.newChannel(website.openStream()); // Create file File file = new File(pathTempFile); FileOutputStream fos = new FileOutputStream(pathTempFile); fos.getChannel().transferFrom(resFile, 0, Long.MAX_VALUE); // Save to MultipartFile FileInputStream input = new FileInputStream(file); multipartFile = new MockMultipartFile("file", file.getName(), "image/png", IOUtils.toByteArray(input)); fos.close(); input.close(); // Set paths attachmentService.setStoragePath(storagePath); attachmentService.setPathDefaultPreview(pathDefaultPreview); }
private void doFile(File f) throws IOException { try { if (f.isDirectory()) { File[] fs = f.listFiles(); for (File fx : fs) { doFile(fx); } } else { if (f.length() < 4096) { // System.out.println("skip too short file " + f +", length=" + f.length()); return; } MFile mfile = mdir.createMFileIfPossible(f.getName()); if (mfile == null) { System.out.println(count + " skip " + f); return; } FileInputStream fos = new FileInputStream(f); w.openMFile(mfile).write(fos).close(); fos.close(); count++; if (count % 100 == 0) { System.out.println(count + " total " + this.mdir.size()); } } } finally { f.delete(); } }
/** * Returns the contents of the file as an array of bytes. If the contents of the file were not yet * cached in memory, they will be loaded from the disk storage and cached. * * @return The contents of the file as an array of bytes. */ public byte[] get() { if (dfos.isInMemory()) { if (cachedContent == null) { cachedContent = dfos.getData(); } return cachedContent; } byte[] fileData = new byte[(int) getSize()]; FileInputStream fis = null; try { fis = new FileInputStream(dfos.getFile()); fis.read(fileData); } catch (IOException e) { fileData = null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } return fileData; }
private void parseCert() { try { FileInputStream fis = new FileInputStream("e:\\rongyifu.der"); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate c = (X509Certificate) cf.generateCertificate(fis); System.out.println("Certficate for " + c.getSubjectDN().getName()); System.out.println("Generated with " + c.getSigAlgName()); System.out.println("== " + c.getSubjectDN().toString()); String publicKey = Base64.encode(c.getPublicKey().getEncoded()); System.out.println("publicKey=" + publicKey); // Map<String, String> map = parseSubjectDN(c.getSubjectDN().toString()); // System.out.println("map: "+map); // String notBefore =c.getNotBefore().toString();//得到开始有效日期 // String notAfter = c.getNotAfter().toString();//得到截止日期 String serialNumber = c.getSerialNumber().toString(16); // 得到序列号 String dn = c.getIssuerDN().getName(); // 得到发行者名 String sigAlgName = c.getSigAlgName(); // 得到签名算法 String algorithm = c.getPublicKey().getAlgorithm(); // 得到公钥算法 SimpleDateFormat intSDF = new SimpleDateFormat("yyyyMMdd"); System.out.println("notBefore=" + intSDF.format(c.getNotBefore())); System.out.println("notAfter=" + intSDF.format(c.getNotAfter())); System.out.println("serialNumber=" + serialNumber); System.out.println("dn=" + dn); System.out.println("sigAlgName=" + sigAlgName); System.out.println("algorithm=" + algorithm); fis.close(); } catch (Exception ex) { ex.printStackTrace(); } }
/** * Reads the given file and returns a byte array. * * @param fileName - file to be read * @return - byte array of the file read. * @throws IOException - in case the file is too large (greater than Integer.MAX_VALUE number of * bytes) or some other IOException occurs. */ public static byte[] fileToBytes(final String fileName) throws IOException { FileInputStream ipStream = null; try { File file = new File(fileName); long fileLength = file.length(); if (fileLength > Integer.MAX_VALUE) { throw new IOException("File too large. Please select a smaller file."); } ipStream = new FileInputStream(file); byte[] bytes = new byte[(int) file.length()]; int bytesRead = ipStream.read(bytes); if (bytesRead < fileLength) { throw new IOException("File not read correctly."); } return bytes; } catch (IOException e) { throw e; } finally { if (ipStream != null) { try { ipStream.close(); } catch (Exception e) { } } } }
/** * Internal copy file method. * * @param srcFile the validated source file, must not be <code>null</code> * @param destFile the validated destination file, must not be <code>null</code> * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { Streams.closeQuietly(output); Streams.closeQuietly(fos); Streams.closeQuietly(input); Streams.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException( "Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } }
public String getJsonFile() { String jString = null; try { File dir = Environment.getExternalStorageDirectory(); File yourFile = new File(dir, "form.json"); FileInputStream stream = new FileInputStream(yourFile); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ jString = Charset.defaultCharset().decode(bb).toString(); } finally { stream.close(); } jObject = new JSONObject(jString); } catch (Exception e) { e.printStackTrace(); } return jObject.toString(); }
public static String getPingzhengContent() { FileInputStream fileIS = null; BufferedReader buf = null; try { File f = new File(Environment.getExternalStorageDirectory() + "/pingzheng.bin"); if (!f.exists()) { f.createNewFile(); } fileIS = new FileInputStream(f.getAbsolutePath()); buf = new BufferedReader(new InputStreamReader(fileIS)); String readString = buf.readLine(); return readString; } catch (Exception e) { e.printStackTrace(); } finally { try { buf.close(); } catch (IOException e) { e.printStackTrace(); } try { fileIS.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
@Before public void setUp() throws Exception { File f = new File(new File(System.getProperty("user.home")), ".jenkins-ci.org"); if (!f.exists()) { LOGGER.warning(f + " doesn't exist. Skipping JDK installation tests"); } else { Properties prop = new Properties(); FileInputStream in = new FileInputStream(f); try { prop.load(in); String u = prop.getProperty("oracle.userName"); String p = prop.getProperty("oracle.password"); if (u == null || p == null) { LOGGER.warning( f + " doesn't contain oracle.userName and oracle.password. Skipping JDK installation tests."); } else { DescriptorImpl d = j.jenkins.getDescriptorByType(DescriptorImpl.class); d.doPostCredential(u, p); } } finally { in.close(); } } }
public Card readCard(File filePath) { Card card = null; try { FileInputStream fis = new FileInputStream(filePath); ObjectInputStream ois = new ObjectInputStream(fis); card = (Card) ois.readObject(); System.out.println( "Card " + card.getName() + " converted mana cost " + card.getConvertedManacost()); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return card; }
private void copyWaveFile(String inFilename, String outFilename) { FileInputStream in = null; FileOutputStream out = null; long totalAudioLen = 0; long totalDataLen = totalAudioLen + 36; long longSampleRate = RECORDER_SAMPLERATE; int channels = 2; long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8; byte[] data = new byte[bufferSize]; try { in = new FileInputStream(inFilename); out = new FileOutputStream(outFilename); totalAudioLen = in.getChannel().size(); totalDataLen = totalAudioLen + 36; // AppLog.logString("File size: " + totalDataLen); WriteWaveFileHeader(out, totalAudioLen, totalDataLen, longSampleRate, channels, byteRate); while (in.read(data) != -1) { out.write(data); } in.close(); out.close(); } catch (FileNotFoundException e) { Log.d("SAN", e.getMessage()); } catch (IOException e) { Log.d("SAN", e.getMessage()); } }
@Override public ArrayList<Compte> findAll(String identifiant) { List<Compte> comptes = new ArrayList<Compte>(); File file = new File(fileName); FileInputStream fileInput = null; try { fileInput = new FileInputStream(file); Properties prop = new Properties(); // load a properties file from class path, inside static method prop.load(fileInput); String line = prop.getProperty(identifiant); // possibilité d'user de split pour créer un map String[] attributs = line.split(":"); for (String cc : attributs[2].split(",")) { String[] attributCC = cc.split("&"); // String numero= // Compte c=new Compte(attributCC[0],intitule,solde);//refaire } } catch (IOException ex) { ex.printStackTrace(); } finally { if (fileInput != null) { try { fileInput.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
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 { // file not found 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) { // thrown if cannot instantiate a File object System.out.println(e.toString()); } finally { if (fis != null) fis.close(); } }
private static void CopyFile(String Origin, String Destination) { File file = new File(Origin); File saveFileat = new File(Destination); if (!saveFileat.exists() && !saveFileat.isDirectory()) { try { FileInputStream inStream = new FileInputStream(file); FileOutputStream outStream = new FileOutputStream(saveFileat); byte[] buffer = new byte[1024]; int length; // copy the file content in bytes while ((length = inStream.read(buffer)) > 0) { outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } }