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

The following examples show how to use java.io.FileInputStream#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Solution.java    From JavaRushTasks with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Scanner reader = new Scanner(System.in);

    FileInputStream f = new FileInputStream(reader.nextLine());

    int min = 0;
    if (f.available() > 0)
        min = f.read();
    while (f.available() > 0) {
        int value = f.read();
        if (value < min)
            min = value;

    }
    f.close();
    System.out.println(min);
}
 
Example 2
Source File: FileUtils.java    From BmapLite with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 读取SDcard里的文件
 *
 * @param file 文件名
 * @return
 */
public static String readFileFromSDCard(File file) {
    String string = null;
    if (isSDCardExists() && file.exists()) {
        try {
            FileInputStream fin = new FileInputStream(file);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            string = new String(buffer);
            fin.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return string;
}
 
Example 3
Source File: Zipfiles.java    From jease with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Zips the given file.
 */
public static File zip(File file) throws IOException {
	String outFilename = file.getAbsolutePath() + ".zip";
	ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
			outFilename));
	FileInputStream in = new FileInputStream(file);
	out.putNextEntry(new ZipEntry(file.getName()));
	byte[] buf = new byte[4096];
	int len;
	while ((len = in.read(buf)) > 0) {
		out.write(buf, 0, len);
	}
	out.closeEntry();
	in.close();
	out.close();
	return new File(outFilename);
}
 
Example 4
Source File: OS.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void encrypt(File infile) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
 byte[] buf = new byte[1024];
    try {
  	  String outname = infile.getAbsolutePath()+".enc";
  	  FileInputStream in = new FileInputStream(infile);
  	  RC4OutputStream out = new RC4OutputStream(new FileOutputStream(outname));
  	  int len;
  	  while((len = in.read(buf)) >= 0) {
  		  if (len > 0)
  			  out.write(buf, 0, len);
  	  }
  	  out.flush();
  	  out.close();
  	  in.close();
    } catch(IOException e) {
      e.printStackTrace();
    }
}
 
Example 5
Source File: FileHandler.java    From Universal-FE-Randomizer with MIT License 6 votes vote down vote up
public FileHandler(File file) throws IOException {
	super();
	this.pathToFile = file.getAbsolutePath();
	
	inputFile = new RandomAccessFile(file, "r");
	fileLength = inputFile.length();
	
	FileInputStream inputStream = new FileInputStream(pathToFile);
	
	CRC32 checksum = new CRC32();
	long currentOffset = 0;
	int numBytes = Math.min(1024, (int)(fileLength - currentOffset));
	while (numBytes > 0) {
		byte[] batch = new byte[numBytes];
		if (inputStream.read(batch) == -1) { break; }
		checksum.update(batch);
		currentOffset += batch.length;
		numBytes = Math.min(1024, (int)(fileLength - currentOffset));
	}
	
	crc32 = checksum.getValue();
	
	inputStream.close();
}
 
Example 6
Source File: CertCrypto.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 文件加密
 * </p>
 * 
 * @param srcFilePath 源文�?
 * @param destFilePath 加密后文�?
 * @param keyStorePath 密钥库存储路�?
 * @param alias 密钥库别�?
 * @param password 密钥库密�?
 * @throws Exception
 */
public static void encryptFileByPrivateKey(String srcFilePath, String destFilePath,KeyStore keyStore, String alias, String password)
        throws Exception {
    // 取得私钥
    PrivateKey privateKey = KeyStoreUtil.getPrivateKey(keyStore, alias, password);
    Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    File srcFile = new File(srcFilePath);
    FileInputStream in = new FileInputStream(srcFile);
    File destFile = new File(destFilePath);
    if (!destFile.getParentFile().exists()) {
        destFile.getParentFile().mkdirs();
    }
    destFile.createNewFile();
    OutputStream out = new FileOutputStream(destFile);   
    byte[] data = new byte[MAX_ENCRYPT_BLOCK];
    byte[] encryptedData;    // 加密�?
    while (in.read(data) != -1) {
        encryptedData = cipher.doFinal(data);
        out.write(encryptedData, 0, encryptedData.length);
        out.flush();
    }
    out.close();
    in.close();
}
 
Example 7
Source File: MediaController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/voice")
    @Menu(type = "resouce" , subtype = "voice" , access = true)
    public void voice(HttpServletResponse response, @Valid String id) throws IOException {
    	File file = new File(path ,id) ;
//    	response.setContentType(Files.probeContentType(Paths.get(file.getAbsolutePath())));  
    	response.setHeader("Content-Type" , "application/octet-stream");
    	response.setHeader("Content-Lenght" , String.valueOf(file.length()));
    	response.setContentLengthLong(file.length());
        response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(file.getName(), "UTF-8"));  
        if(file.exists() && file.isFile()){
    		FileInputStream input = new FileInputStream(file) ;
    		OutputStream output = response.getOutputStream() ; 
    		byte[] data = new byte[1024] ;
    		int len = 0 ;
    		while((len = input.read(data))>0) {
    			output.write(data , 0  , len);
    		}
    		output.flush();
    		input.close();
    	}
    }
 
Example 8
Source File: SendBitmapWorkerTask.java    From iBeebo with GNU General Public License v3.0 6 votes vote down vote up
private boolean copy(String fileFrom, String fileTo) {
    try {
        FileInputStream in = new FileInputStream(fileFrom);
        FileOutputStream out = new FileOutputStream(fileTo);
        byte[] bt = new byte[1024];
        int count;
        while ((count = in.read(bt)) > 0) {
            out.write(bt, 0, count);
        }
        in.close();
        out.close();
        return true;
    } catch (IOException ex) {
        return false;
    }
}
 
Example 9
Source File: FileUtils.java    From fangzhuishushenqi with Apache License 2.0 6 votes vote down vote up
public static byte[] getBytesFromFile(File f) {
    if (f == null) {
        return null;
    }
    try {
        FileInputStream stream = new FileInputStream(f);
        ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1000];
        for (int n; (n = stream.read(b)) != -1; ) {
            out.write(b, 0, n);
        }
        stream.close();
        out.close();
        return out.toByteArray();
    } catch (IOException e) {
    }
    return null;
}
 
Example 10
Source File: CopyAviDemo.java    From Java with Artistic License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
	// ��װ����Դ
	FileInputStream fis = new FileInputStream("e:\\DOS����.avi");
	// ��װĿ�ĵ�
	FileOutputStream fos = new FileOutputStream("copy.avi");

	// �����
	int by = 0;
	while ((by = fis.read()) != -1) {
		fos.write(by);
	}

	// �ͷ���Դ
	fos.close();
	fis.close();
}
 
Example 11
Source File: ImageMessage.java    From BluetoothSocket with Apache License 2.0 6 votes vote down vote up
@Override
public void writeContent(OutputStream outputStream) throws IOException {
    outputStream.write(creatHeader());
    outputStream.write(0xA);
    outputStream.write(0xD);

    FileInputStream fio = new FileInputStream(mContent);


    byte[] buffer = new byte[64 * 1024];
    int length = 0;
    while ((length = fio.read(buffer)) >= 0) {
        outputStream.write(buffer, 0, length);
        outputStream.flush();
    }

}
 
Example 12
Source File: BasicJavaClientREST.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
/**
 * Write document using BytesHandle with metadata
 * 
 * @param client
 * @param filename
 * @param uri
 * @param metadataHandle
 * @param type
 * @throws IOException
 */
public void writeDocumentUsingBytesHandle(DatabaseClient client, String filename, String uri, DocumentMetadataHandle metadataHandle, String type) throws IOException
{
  // get the content to bytes
  File file = new File("src/test/java/com/marklogic/client/functionaltest/data/" + filename);
  FileInputStream fis = new FileInputStream(file);
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buf = new byte[1024];
  for (int readNum; (readNum = fis.read(buf)) != -1;)
  {
    bos.write(buf, 0, readNum);
  }

  byte[] bytes = bos.toByteArray();

  fis.close();
  bos.close();

  // create doc manager
  DocumentManager docMgr = null;
  docMgr = documentManagerSelector(client, docMgr, type);

  String docId = uri + filename;

  // create handle
  BytesHandle contentHandle = new BytesHandle();
  contentHandle.set(bytes);

  // write the doc
  docMgr.write(docId, metadataHandle, contentHandle);

  System.out.println("Write " + docId + " to the database");
}
 
Example 13
Source File: Basic.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    URI uri = t.getRequestURI();

    debug("Server: received request for " + uri);
    String path = uri.getPath();
    if (path.endsWith("a.jar"))
        aDotJar++;
    else if (path.endsWith("b.jar"))
        bDotJar++;
    else if (path.endsWith("c.jar"))
        cDotJar++;
    else
        System.out.println("Unexpected resource request" + path);

    while (is.read() != -1);
    is.close();

    File file = new File(docsDir, path);
    if (!file.exists())
        throw new RuntimeException("Error: request for " + file);
    long clen = file.length();
    t.sendResponseHeaders (200, clen);
    OutputStream os = t.getResponseBody();
    FileInputStream fis = new FileInputStream(file);
    try {
        byte[] buf = new byte [16 * 1024];
        int len;
        while ((len=fis.read(buf)) != -1) {
            os.write (buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    fis.close();
    os.close();
}
 
Example 14
Source File: Slice.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
public ByteBuffer getData() {
    try {
        byte[] input = new byte[1024];
        byte[] output = new byte[1024];
        FileInputStream fin = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Inflater inflater = new Inflater(true);

        while (true) {
            int numRead = fin.read(input);
            if (numRead != -1) {
                inflater.setInput(input, 0, numRead);
            }

            int numDecompressed;
            while ((numDecompressed = inflater.inflate(output, 0, output.length)) != 0) {
                bos.write(output, 0, numDecompressed);
            }

            if (inflater.finished()) {
                break;
            } else if (inflater.needsInput()) {
                continue;
            }
        }

        inflater.end();
        ByteBuffer result = ByteBuffer.wrap(bos.toByteArray(), 0, bos.size());

        bos.close();
        fin.close();

        return result;
    } catch (Exception e) {
        FileLog.e(e);
    }

    return null;
}
 
Example 15
Source File: AIFFCp037.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void printFile(String filename) throws Exception {
    File file = new File(filename);
    FileInputStream fis = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    fis.read(data);
    String s = "";
    for (int i=0; i<data.length; i++) {
        s+=getString(data[i])+", ";
        if (s.length()>72) {
            System.out.println(s);
            s="";
        }
    }
    System.out.println(s);
}
 
Example 16
Source File: ModuleImportContextualCompletionProposal.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
private static String readString(FileInputStream is, int maxLen) throws IOException {
    StringBuilder sb = new StringBuilder();
    while (true) {
        int ich = is.read();
        char ch = (char)ich;
        if (ch == EOS || ich < 0) {
            break;
        }
        sb.append(ch);
        if (sb.length() >= maxLen) {
            throw new IOException("Sym file reader: string length > " + maxLen);
        }
    }
    return sb.toString();
}
 
Example 17
Source File: AuZeroLength.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void printFile(String filename) throws Exception {
    File file = new File(filename);
    FileInputStream fis = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    fis.read(data);
    String s = "";
    for (int i=0; i<data.length; i++) {
        s+=getString(data[i])+", ";
        if (s.length()>72) {
            System.out.println(s);
            s="";
        }
    }
    System.out.println(s);
}
 
Example 18
Source File: TestFileOutputCommitter.java    From hadoop with Apache License 2.0 5 votes vote down vote up
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
Source File: JarHelper.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Recursively jars up the given path under the given directory.
 */
private void jarDir(File dirOrFile2jar, JarOutputStream jos, String path)
	throws IOException {
	if (mVerbose) {
		System.out.println("checking " + dirOrFile2jar);
	}
	if (dirOrFile2jar.isDirectory()) {
		String[] dirList = dirOrFile2jar.list();
		String subPath = (path == null) ? "" : (path + dirOrFile2jar.getName() + SEP);
		if (path != null) {
			JarEntry je = new JarEntry(subPath);
			je.setTime(dirOrFile2jar.lastModified());
			jos.putNextEntry(je);
			jos.flush();
			jos.closeEntry();
		}
		for (int i = 0; i < dirList.length; i++) {
			File f = new File(dirOrFile2jar, dirList[i]);
			jarDir(f, jos, subPath);
		}
	} else if (dirOrFile2jar.exists()) {
		if (dirOrFile2jar.getCanonicalPath().equals(mDestJarName)) {
			if (mVerbose) {
				System.out.println("skipping " + dirOrFile2jar.getPath());
			}
			return;
		}

		if (mVerbose) {
			System.out.println("adding " + dirOrFile2jar.getPath());
		}
		FileInputStream fis = new FileInputStream(dirOrFile2jar);
		try {
			JarEntry entry = new JarEntry(path + dirOrFile2jar.getName());
			entry.setTime(dirOrFile2jar.lastModified());
			jos.putNextEntry(entry);
			while ((mByteCount = fis.read(mBuffer)) != -1) {
				jos.write(mBuffer, 0, mByteCount);
				if (mVerbose) {
					System.out.println("wrote " + mByteCount + " bytes");
				}
			}
			jos.flush();
			jos.closeEntry();
		} catch (IOException ioe) {
			throw ioe;
		} finally {
			fis.close();
		}
	}
}
 
Example 20
Source File: TestConcatenatedCompressedInput.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Test using the raw Inflater codec for reading gzip files.
 */
@Test
public void testPrototypeInflaterGzip() throws IOException {
  CompressionCodec gzip = new GzipCodec();  // used only for file extension
  localFs.delete(workDir, true);            // localFs = FileSystem instance

  System.out.println(COLOR_BR_BLUE + "testPrototypeInflaterGzip() using " +
    "non-native/Java Inflater and manual gzip header/trailer parsing" +
    COLOR_NORMAL);

  // copy prebuilt (correct!) version of concat.gz to HDFS
  final String fn = "concat" + gzip.getDefaultExtension();
  Path fnLocal = new Path(System.getProperty("test.concat.data", "/tmp"), fn);
  Path fnHDFS  = new Path(workDir, fn);
  localFs.copyFromLocalFile(fnLocal, fnHDFS);

  final FileInputStream in = new FileInputStream(fnLocal.toString());
  assertEquals("concat bytes available", 148, in.available());

  // should wrap all of this header-reading stuff in a running-CRC wrapper
  // (did so in BuiltInGzipDecompressor; see below)

  byte[] compressedBuf = new byte[256];
  int numBytesRead = in.read(compressedBuf, 0, 10);
  assertEquals("header bytes read", 10, numBytesRead);
  assertEquals("1st byte", 0x1f, compressedBuf[0] & 0xff);
  assertEquals("2nd byte", 0x8b, compressedBuf[1] & 0xff);
  assertEquals("3rd byte (compression method)", 8, compressedBuf[2] & 0xff);

  byte flags = (byte)(compressedBuf[3] & 0xff);
  if ((flags & 0x04) != 0) {   // FEXTRA
    numBytesRead = in.read(compressedBuf, 0, 2);
    assertEquals("XLEN bytes read", 2, numBytesRead);
    int xlen = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
    in.skip(xlen);
  }
  if ((flags & 0x08) != 0) {   // FNAME
    while ((numBytesRead = in.read()) != 0) {
      assertFalse("unexpected end-of-file while reading filename",
                  numBytesRead == -1);
    }
  }
  if ((flags & 0x10) != 0) {   // FCOMMENT
    while ((numBytesRead = in.read()) != 0) {
      assertFalse("unexpected end-of-file while reading comment",
                  numBytesRead == -1);
    }
  }
  if ((flags & 0xe0) != 0) {   // reserved
    assertTrue("reserved bits are set??", (flags & 0xe0) == 0);
  }
  if ((flags & 0x02) != 0) {   // FHCRC
    numBytesRead = in.read(compressedBuf, 0, 2);
    assertEquals("CRC16 bytes read", 2, numBytesRead);
    int crc16 = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
  }

  // ready to go!  next bytes should be start of deflated stream, suitable
  // for Inflater
  numBytesRead = in.read(compressedBuf);

  // Inflater docs refer to a "dummy byte":  no clue what that's about;
  // appears to work fine without one
  byte[] uncompressedBuf = new byte[256];
  Inflater inflater = new Inflater(true);

  inflater.setInput(compressedBuf, 0, numBytesRead);
  try {
    int numBytesUncompressed = inflater.inflate(uncompressedBuf);
    String outString =
      new String(uncompressedBuf, 0, numBytesUncompressed, "UTF-8");
    System.out.println("uncompressed data of first gzip member = [" +
                       outString + "]");
  } catch (java.util.zip.DataFormatException ex) {
    throw new IOException(ex.getMessage());
  }

  in.close();
}