Java Code Examples for java.io.FileInputStream.read()

The following are Jave code examples for showing how to use read() of the java.io.FileInputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: i18n-maven-plugin   File: FileUtil.java   View Source Code Vote up 6 votes
public static void copyFile(File f1, File f2) throws Exception {
	if (!f2.getParentFile().exists()) {
		if (!f2.getParentFile().mkdirs()) {
			throw new Exception("Create file '" + f2.getName() + "' directory error !");
		}
	}
	try {
		int length = 2097152;
		FileInputStream in = new FileInputStream(f1);
		FileOutputStream out = new FileOutputStream(f2);
		byte[] buffer = new byte[length];
		while (true) {
			int ins = in.read(buffer);
			if (ins == -1) {
				in.close();
				out.flush();
				out.close();
			} else
				out.write(buffer, 0, ins);
		}
	} catch (Exception e) {
	}
}
 
Example 2
Project: uavstack   File: IOHelper.java   View Source Code Vote up 6 votes
/**
 * readFile
 * 
 * @param destination
 * @return
 * @throws IOException
 */
public static byte[] readFile(String destination) throws IOException {

    File temp = new File(destination);

    if (temp.exists()) {
        FileInputStream fis = new FileInputStream(temp);
        byte[] data = new byte[(int) temp.length()];
        try {
            fis.read(data);
        }
        finally {
            fis.close();
        }
        return data;
    }

    return new byte[0];
}
 
Example 3
Project: BigQueryStudy   File: GZipHelper.java   View Source Code Vote up 6 votes
public static String compressGzipFile(String file, String gzipFile) {
    try {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(gzipFile);
        GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
        byte[] buffer = new byte[1024];
        int len;
        while((len=fis.read(buffer)) != -1){
            gzipOS.write(buffer, 0, len);
        }
        //close resources
        gzipOS.close();
        fos.close();
        fis.close();
        System.out.println("A json.gz file was created: " + gzipFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return gzipFile;
}
 
Example 4
Project: letv   File: bu.java   View Source Code Vote up 6 votes
public static String a(File file) {
    byte[] bArr = new byte[1024];
    try {
        if (!file.isFile()) {
            return "";
        }
        MessageDigest instance = MessageDigest.getInstance(CommonUtils.MD5_INSTANCE);
        FileInputStream fileInputStream = new FileInputStream(file);
        while (true) {
            int read = fileInputStream.read(bArr, 0, 1024);
            if (read != -1) {
                instance.update(bArr, 0, read);
            } else {
                fileInputStream.close();
                BigInteger bigInteger = new BigInteger(1, instance.digest());
                return String.format("%1$032x", new Object[]{bigInteger});
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 5
Project: java-codes   File: UnsafeTest.java   View Source Code Vote up 6 votes
/**
 * 通过Unsafe的defineClass方法在内存中创建一个Class对象
 *
 * @throws Exception
 */
@Test
public void test3() throws Exception {
    //读取Class文件
    File file = new File("E:\\classes\\Test.class");
    FileInputStream input = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    input.read(data);
    input.close();
    //创建Class对象
    //Class clazz = unsafe.defineClass("Test", data, 0, data.length);//这个方法在Java 8 没了。
    Class clazz = unsafe.defineClass("Test", data, 0, data.length, null, null);
    //通过反射创建示例调用方法
    Object instance = clazz.newInstance();
    Method method = clazz.getMethod("say", null);
    method.invoke(instance);//Hello
}
 
Example 6
Project: GitHub   File: DataKeeper.java   View Source Code Vote up 6 votes
/**
 * 存储缓存文件 返回文件绝对路径
 * @param file
 * 		要存储的文件
 * @param type
 * 		文件的类型
 *		IMAGE = "imgae";							//图片         
 *		VIDEO = "video";							//视频        
 *		VOICE = "voice";							//语音         
 *		 = "voice";							//语音         
 * @return	存储文件的绝对路径名
 * 		若SDCard不存在返回null
 */
public static String storeFile(File file, String type) {

	if(!hasSDCard()) {
		return null;
	}
	String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
	byte[] data = null;
	try {
		FileInputStream in = new FileInputStream(file);
		data = new byte[in.available()];
		in.read(data, 0, data.length);
		in.close();
	} catch (IOException e) {
		Log.e(TAG, "storeFile  try { FileInputStream in = new FileInputStream(file); ... >>" +
				" } catch (IOException e) {\n" + e.getMessage());
	}
	return storeFile(data, suffix, type);
}
 
Example 7
Project: GitHub   File: DataKeeper.java   View Source Code Vote up 6 votes
/**
 * 存储缓存文件 返回文件绝对路径
 * @param file
 * 		要存储的文件
 * @param type
 * 		文件的类型
 *		IMAGE = "imgae";							//图片         
 *		VIDEO = "video";							//视频        
 *		VOICE = "voice";							//语音         
 *		 = "voice";							//语音         
 * @return	存储文件的绝对路径名
 * 		若SDCard不存在返回null
 */
public static String storeFile(File file, String type) {

	if(!hasSDCard()) {
		return null;
	}
	String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
	byte[] data = null;
	try {
		FileInputStream in = new FileInputStream(file);
		data = new byte[in.available()];
		in.read(data, 0, data.length);
		in.close();
	} catch (IOException e) {
		Log.e(TAG, "storeFile  try { FileInputStream in = new FileInputStream(file); ... >>" +
				" } catch (IOException e) {\n" + e.getMessage());
	}
	return storeFile(data, suffix, type);
}
 
Example 8
Project: LoginCrawler   File: MD5Utils.java   View Source Code Vote up 6 votes
public static Map<String, Object> calculateDigest(File file) throws IOException {
    Map<String, Object> map = new HashMap<String, Object>();
    FileInputStream is = new FileInputStream(file);
    long size = 0;
    String digest = StringUtils.EMPTY;
    try {
        MessageDigest md = MD5Utils.getDigest();
        byte[] buffer = new byte[1024];
        while (true) {
            int len = is.read(buffer);
            if (len < 0) {
                break;
            }
            size += len;
            md.update(buffer, 0, len);
        }
        byte[] digests = md.digest();
        digest = MD5Utils.encodeHexString(digests);
        map.put("size", size);
        map.put("digest", digest);
    } finally {
        is.close();
    }
    return map;
}
 
Example 9
Project: SpotSpotter   File: BMPReader.java   View Source Code Vote up 6 votes
public void read(FileInputStream fs) throws IOException {
	final int bflen = 14;
	final byte bf[] = new byte[bflen];
	fs.read(bf, 0, bflen);
	final int bilen = 40;
	final byte bi[] = new byte[bilen];
	fs.read(bi, 0, bilen);
	iSize = constructInt(bf, 2);
	ibiSize = constructInt(bi, 2);
	iWidth = constructInt(bi, 4);
	iHeight = constructInt(bi, 8);
	iPlanes = constructShort(bi, 12);
	iBitcount = constructShort(bi, 14);
	iCompression = constructInt(bi, 16);
	iSizeimage = constructInt(bi, 20);
	iXpm = constructInt(bi, 24);
	iYpm = constructInt(bi, 28);
	iClrused = constructInt(bi, 32);
	iClrimp = constructInt(bi, 36);
}
 
Example 10
Project: JAddOn   File: JAppZip.java   View Source Code Vote up 6 votes
/**
 * Zip it
 */
public void zipIt(){
    byte[] buffer = new byte[1024];
    try{
        FileOutputStream fos = new FileOutputStream(OUTPUT_ZIP_FILE);
        ZipOutputStream zos = new ZipOutputStream(fos);
        //System.out.println("Output to Zip : " + zipFile);
        for(String file : this.fileList){
            //System.out.println("File Added : " + file);
            ZipEntry ze= new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(SOURCE_FOLDER.getAbsolutePath() + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
       }
       zos.closeEntry();
       zos.close();
       //System.out.println("Done");
    } catch (IOException ex) {
        ex.printStackTrace();   
    }
}
 
Example 11
Project: olami-java-client-sdk   File: SpeechRecognizer.java   View Source Code Vote up 6 votes
/**
 * Request to upload the specified audio for speech recognition.
 * 
 * @param identifier - Identifier CookieSet.
 * @param filePath - The path of the audio file.
 *                   Wave Header is required if it is a Wave audio.
 * @param audioType - Audio type: 
 *                    AUDIO_TYPE_PCM_RAW for PCM raw data.
 *                    AUDIO_TYPE_PCM_WAVE for Wave audio.
 * @param isFinalAudio - TRUE if this is the last audio of a speech input.
 * @return API response with the audio uploading status.
 * @throws IOException File handling or HTTP connection failed, or other exceptions.
 * @throws NoSuchAlgorithmException Failed to create signature.
 */
public APIResponse uploadAudio(
		CookieSet identifier,
		String filePath,
		int audioType,
		boolean isFinalAudio
) throws IOException, NoSuchAlgorithmException {
	
	File file = new File(filePath);
	
	if (file == null || (!file.exists())) {
		throw new FileNotFoundException("File not found: " + filePath);
	}
	
	FileInputStream fileIn = new FileInputStream(file);
	byte[] fileData = new byte[(int) file.length()];
	fileIn.read(fileData);
	fileIn.close();
	
	return uploadAudio(identifier, fileData, audioType, isFinalAudio);
	
}
 
Example 12
Project: SER316-Ingolstadt   File: ProjectPackager.java   View Source Code Vote up 5 votes
/**
 * Packs all files in the given directory into the given ZIP stream.
 * Also recurses down into subdirectories.
 */
public static void PackDirectory( String startingDirectory,
                                File theDirectory,
                                ZipOutputStream theZIPStream )
throws java.io.IOException
{
   File[] theFiles = theDirectory.listFiles();
   File stDirectory = new File(startingDirectory);
   System.out.println("Path="+stDirectory.getPath()+";length="+stDirectory.getPath().length() + "==>"+theFiles[0]);
   int j = stDirectory.getPath().length();
   for ( int i=0 ; i<theFiles.length ; i++ )
   {
      String sRelPath = theFiles[i].getPath().substring(j);
      if ( theFiles[i].isDirectory() )
      {
         // create a directory entry.
         // directory entries must be terminated by a slash!
         ZipEntry theEntry = new ZipEntry("."+sRelPath+"/" );
         theZIPStream.putNextEntry(theEntry);
         theZIPStream.closeEntry();

         // recurse down
         PackDirectory( startingDirectory, theFiles[i], theZIPStream );
      }
      else // regular file
      { 
        File f = theFiles[i];
        ZipEntry ze = new ZipEntry("."+sRelPath);
        FileInputStream in = new FileInputStream(f);
        byte[] data = new byte[(int) f.length()];
        in.read(data);
        in.close();
        theZIPStream.putNextEntry(ze);
        theZIPStream.write(data);
        theZIPStream.closeEntry();           
      }
   }
}
 
Example 13
Project: android-project-gallery   File: JsonStreamerEntity.java   View Source Code Vote up 5 votes
private void writeToFromFile(OutputStream os, RequestParams.FileWrapper wrapper)
        throws IOException {

    // Send the meta data.
    writeMetaData(os, wrapper.file.getName(), wrapper.contentType);

    int bytesRead, bytesWritten = 0, totalSize = (int) wrapper.file.length();

    // Open the file for reading.
    FileInputStream in = new FileInputStream(wrapper.file);

    // Upload the file's contents in Base64.
    Base64OutputStream bos =
            new Base64OutputStream(os, Base64.NO_CLOSE | Base64.NO_WRAP);

    // Read from file until no more data's left to read.
    while ((bytesRead = in.read(buffer)) != -1) {
        bos.write(buffer, 0, bytesRead);
        bytesWritten += bytesRead;
        progressHandler.sendProgressMessage(bytesWritten, totalSize);
    }

    // Close the Base64 output stream.
    AsyncHttpClient.silentCloseOutputStream(bos);

    // End the meta data.
    endMetaData(os);

    // Safely close the input stream.
    AsyncHttpClient.silentCloseInputStream(in);
}
 
Example 14
Project: Cable-Android   File: TextSecureSessionStore.java   View Source Code Vote up 5 votes
private byte[] readBlob(FileInputStream in) throws IOException {
  int length       = readInteger(in);
  byte[] blobBytes = new byte[length];

  in.read(blobBytes, 0, blobBytes.length);
  return blobBytes;
}
 
Example 15
Project: PeSanKita-lib   File: AttachmentCipherInputStream.java   View Source Code Vote up 5 votes
private void verifyMac(File file, Mac mac, Optional<byte[]> theirDigest)
    throws FileNotFoundException, InvalidMacException
{
  try {
    MessageDigest   digest        = MessageDigest.getInstance("SHA256");
    FileInputStream fin           = new FileInputStream(file);
    int             remainingData = Util.toIntExact(file.length()) - mac.getMacLength();
    byte[]          buffer        = new byte[4096];

    while (remainingData > 0) {
      int read = fin.read(buffer, 0, Math.min(buffer.length, remainingData));
      mac.update(buffer, 0, read);
      digest.update(buffer, 0, read);
      remainingData -= read;
    }

    byte[] ourMac   = mac.doFinal();
    byte[] theirMac = new byte[mac.getMacLength()];
    Util.readFully(fin, theirMac);

    if (!MessageDigest.isEqual(ourMac, theirMac)) {
      throw new InvalidMacException("MAC doesn't match!");
    }

    byte[] ourDigest = digest.digest(theirMac);

    if (theirDigest.isPresent() && !MessageDigest.isEqual(ourDigest, theirDigest.get())) {
      throw new InvalidMacException("Digest doesn't match!");
    }

  } catch (IOException | ArithmeticException e1) {
    throw new InvalidMacException(e1);
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 16
Project: SER316-Aachen   File: ProjectPackager.java   View Source Code Vote up 5 votes
/**
 * Packs all files in the given directory into the given ZIP stream.
 * Also recurses down into subdirectories.
 */
public static void PackDirectory( String startingDirectory,
                                File theDirectory,
                                ZipOutputStream theZIPStream )
throws java.io.IOException
{
   File[] theFiles = theDirectory.listFiles();
   File stDirectory = new File(startingDirectory);
   System.out.println("Path="+stDirectory.getPath()+";length="+stDirectory.getPath().length() + "==>"+theFiles[0]);
   int j = stDirectory.getPath().length();
   for ( int i=0 ; i<theFiles.length ; i++ )
   {
      String sRelPath = theFiles[i].getPath().substring(j);
      if ( theFiles[i].isDirectory() )
      {
         // create a directory entry.
         // directory entries must be terminated by a slash!
         ZipEntry theEntry = new ZipEntry("."+sRelPath+"/" );
         theZIPStream.putNextEntry(theEntry);
         theZIPStream.closeEntry();

         // recurse down
         PackDirectory( startingDirectory, theFiles[i], theZIPStream );
      }
      else // regular file
      { 
        File f = theFiles[i];
        ZipEntry ze = new ZipEntry("."+sRelPath);
        FileInputStream in = new FileInputStream(f);
        byte[] data = new byte[(int) f.length()];
        in.read(data);
        in.close();
        theZIPStream.putNextEntry(ze);
        theZIPStream.write(data);
        theZIPStream.closeEntry();           
      }
   }
}
 
Example 17
Project: letv   File: FileUtils.java   View Source Code Vote up 5 votes
public static String getApiFileCache(Context context, String cacheName) {
    if (context == null || TextUtils.isEmpty(cacheName)) {
        return null;
    }
    FileInputStream fis = null;
    try {
        fis = context.openFileInput(cacheName);
        if (fis != null) {
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            String str = new String(buffer);
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return str;
        } else if (fis == null) {
            return null;
        } else {
            try {
                fis.close();
                return null;
            } catch (Exception e2) {
                e2.printStackTrace();
                return null;
            }
        }
    } catch (Exception e22) {
        e22.printStackTrace();
        if (fis == null) {
            return null;
        }
        try {
            fis.close();
            return null;
        } catch (Exception e222) {
            e222.printStackTrace();
            return null;
        }
    } catch (Throwable th) {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e2222) {
                e2222.printStackTrace();
            }
        }
    }
}
 
Example 18
Project: hadoop   File: TestFileOutputCommitter.java   View Source Code Vote up 5 votes
public static String slurp(File f) throws IOException {
  int len = (int) f.length();
  byte[] buf = new byte[len];
  FileInputStream in = new FileInputStream(f);
  String contents = null;
  try {
    in.read(buf, 0, len);
    contents = new String(buf, "UTF-8");
  } finally {
    in.close();
  }
  return contents;
}
 
Example 19
Project: openjdk-jdk10   File: ZoneInfoFile.java   View Source Code Vote up 5 votes
/**
 * Reads the specified file under &lt;java.home&gt;/lib/zi into a buffer.
 * @return the buffer, or null if any I/O error occurred.
 */
private static byte[] readZoneInfoFile(final String fileName) {
    if (fileName.indexOf("..") >= 0) {
        return null;
    }
    byte[] buffer = null;
    File file = new File(ziDir, fileName);
    try {
        int filesize = (int)file.length();
        if (filesize > 0) {
            FileInputStream fis = new FileInputStream(file);
            buffer = new byte[filesize];
            try {
                if (fis.read(buffer) != filesize) {
                    throw new IOException("read error on " + fileName);
                }
            } finally {
                fis.close();
            }
        }
    } catch (Exception ex) {
        if (!(ex instanceof FileNotFoundException) || JAVAZM_FILE_NAME.equals(fileName)) {
            System.err.println("ZoneInfoOld: " + ex.getMessage());
        }
    }
    return buffer;
}
 
Example 20
Project: neural-algorithms   File: IdxManager.java   View Source Code Vote up 4 votes
public void load() throws IOException {

        inImage = new FileInputStream(inputImagePath);
        inLabel = new FileInputStream(inputLabelPath);

        int magicNumberImages = (inImage.read() << 24) | (inImage.read() << 16)
                | (inImage.read() << 8) | (inImage.read());
        int numberOfImages = (inImage.read() << 24) | (inImage.read() << 16)
                | (inImage.read() << 8) | (inImage.read());
        numOfRows = (inImage.read() << 24) | (inImage.read() << 16)
                | (inImage.read() << 8) | (inImage.read());
        numOfCols = (inImage.read() << 24) | (inImage.read() << 16)
                | (inImage.read() << 8) | (inImage.read());

        int magicNumberLabels = (inLabel.read() << 24) | (inLabel.read() << 16)
                | (inLabel.read() << 8) | (inLabel.read());
        int numberOfLabels = (inLabel.read() << 24) | (inLabel.read() << 16)
                | (inLabel.read() << 8) | (inLabel.read());

        BufferedImage image = new BufferedImage(numOfCols,
                numOfRows, BufferedImage.TYPE_INT_ARGB);

        int numberOfPixels = numOfRows * numOfCols;
        int[] imgPixels = new int[numberOfPixels];
        int[] imgVals = new int[numberOfPixels];
        data = new double[numberOfLabels][];
        pixelData = new int[numberOfLabels][];
        labels = new double[numberOfLabels][10];
        labelsVec = new double[numberOfLabels];

        for (int i = 0; i < numberOfImages; i++) {

            for (int p = 0; p < numberOfPixels; p++) {
                int gray = 255 - inImage.read();
                imgPixels[p] = 0xFF000000 | (gray << 16) | (gray << 8) | gray;
                imgVals[p] = gray;
            }

            int label = inLabel.read();

            data[i] = Arrays.stream(imgVals).asDoubleStream().toArray();
            pixelData[i] = imgPixels;
            labels[i][label] = 1.0;
            labelsVec[i] = label;

            if (writeImg) {
                File outputfile = new File(outputPath + "img" + i + ".png");
                image.setRGB(0, 0, numOfCols, numOfRows, imgPixels, 0,
                        numOfCols);
                ImageIO.write(image, "png", outputfile);
            }

            if (i % 1000 == 0) {
                System.out.println("Number of images extracted: " + i);
                //return;
            }
        }
    }