List of usage examples for java.io FileInputStream available
public int available() throws IOException
From source file:edu.vt.cs.cnd2xsd.Cnd2XsdConverter.java
private void loadPropertyMap(String path) { FileInputStream stream = null; try {/*from w w w .ja va 2s .com*/ stream = new FileInputStream(path); attrMap = new HashMap<String, String[]>(); byte[] buffer = new byte[512]; StringBuffer stBuffer = new StringBuffer(); while (stream.available() > 0) { int n = stream.read(buffer, 0, 512); stBuffer.append(new String(buffer, 0, n)); } String value = stBuffer.substring(0); //now lets split the value into multiple lines String[] lines = value.split("\n"); log.debug("Buffer contains :{} lines", lines.length); for (String line : lines) { String[] kvs = line.split("#"); String key = kvs[0]; String[] values = null; if (kvs.length > 1) { values = kvs[1].split(","); log.debug("Key: {} Value:{}", key, kvs[1]); } attrMap.put(key, values); } } catch (IOException ex) { log.error("Exception caught:", ex); } finally { try { stream.close(); } catch (IOException ex) { log.error("Exception caught:", ex); } } }
From source file:org.apache.hadoop.mapred.TestConcatenatedCompressedInput.java
/** * Test using the raw Inflater codec for reading gzip files. *//* w ww. j a v a 2 s .co m*/ @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(); }
From source file:com.yunmel.syncretic.utils.io.IOUtils.java
/** * //from www.j a v a2 s .c o m * * @param filePath * @param fileName ?? * @param inline ?? * @throws Exception */ public static void downloadFile(HttpServletResponse response, File file, String fileName, boolean inline) throws Exception { OutputStream outp = null; FileInputStream br = null; int len = 0; try { br = new FileInputStream(file); response.reset(); outp = response.getOutputStream(); outp.flush(); response.setContentType("application/octet-stream"); response.setContentLength((int) file.length()); String header = (inline ? "inline" : "attachment") + ";filename=" + new String(fileName.getBytes(), "ISO8859-1"); response.addHeader("Content-Disposition", header); byte[] buf = new byte[1024]; while ((len = br.read(buf)) != -1) { outp.write(buf, 0, len); } outp.flush(); outp.close(); } finally { if (br != null) { if (0 == br.available()) { br.close(); } } } }
From source file:net.ustyugov.jtalk.activity.vcard.VCardActivity.java
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); service = JTalkService.getInstance(); account = getIntent().getStringExtra("account"); jid = getIntent().getStringExtra("jid"); setTheme(Colors.isLight ? R.style.AppThemeLight : R.style.AppThemeDark); setContentView(R.layout.paged_activity); getActionBar().setDisplayHomeAsUpEnabled(true); setTitle("vCard"); getActionBar().setSubtitle(jid);//from w w w . ja va 2 s . c o m if (service.getConferencesHash(account).containsKey(StringUtils.parseBareAddress(jid))) { Presence p = service.getConferencesHash(account).get(StringUtils.parseBareAddress(jid)) .getOccupantPresence(jid); if (p != null) { MUCUser mucUser = (MUCUser) p.getExtension("x", "http://jabber.org/protocol/muc#user"); if (mucUser != null) { String j = mucUser.getItem().getJid(); if (j != null && j.length() > 3) getActionBar().setSubtitle(j); } } } LinearLayout linear = (LinearLayout) findViewById(R.id.linear); linear.setBackgroundColor(Colors.BACKGROUND); LayoutInflater inflater = LayoutInflater.from(this); View aboutPage = inflater.inflate(R.layout.vcard_about, null); View homePage = inflater.inflate(R.layout.vcard_home, null); View workPage = inflater.inflate(R.layout.vcard_work, null); View avatarPage = inflater.inflate(R.layout.vcard_avatar, null); View statusPage = inflater.inflate(R.layout.list_activity, null); first = (MyTextView) aboutPage.findViewById(R.id.firstname); middle = (MyTextView) aboutPage.findViewById(R.id.middlename); last = (MyTextView) aboutPage.findViewById(R.id.lastname); nick = (MyTextView) aboutPage.findViewById(R.id.nickname); bday = (MyTextView) aboutPage.findViewById(R.id.bday); url = (MyTextView) aboutPage.findViewById(R.id.url); about = (MyTextView) aboutPage.findViewById(R.id.desc); ctry = (MyTextView) homePage.findViewById(R.id.ctry); locality = (MyTextView) homePage.findViewById(R.id.locality); street = (MyTextView) homePage.findViewById(R.id.street); emailHome = (MyTextView) homePage.findViewById(R.id.homemail); phoneHome = (MyTextView) homePage.findViewById(R.id.homephone); org = (MyTextView) workPage.findViewById(R.id.org); unit = (MyTextView) workPage.findViewById(R.id.unit); role = (MyTextView) workPage.findViewById(R.id.role); emailWork = (MyTextView) workPage.findViewById(R.id.workmail); phoneWork = (MyTextView) workPage.findViewById(R.id.workphone); av = (ImageView) avatarPage.findViewById(R.id.av); av.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { File file = new File(Constants.PATH + jid.replaceAll("/", "%")); Uri uri = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, "image/*"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(intent); } catch (ActivityNotFoundException ignored) { } } }); av.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { String fname = Constants.PATH + jid.replaceAll("/", "%"); String saveto = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Avatars/"; File folder = new File(saveto); folder.mkdirs(); try { FileInputStream fis = new FileInputStream(fname); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); FileOutputStream fos = new FileOutputStream(saveto + "/" + jid.replaceAll("/", "%") + ".png"); fos.write(buffer); fos.close(); Toast.makeText(VCardActivity.this, "Copied to " + saveto, Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(VCardActivity.this, "Failed to copy", Toast.LENGTH_LONG).show(); } return true; } }); statusProgress = (ProgressBar) statusPage.findViewById(R.id.progress); aboutProgress = (ProgressBar) aboutPage.findViewById(R.id.progress); homeProgress = (ProgressBar) homePage.findViewById(R.id.progress); workProgress = (ProgressBar) workPage.findViewById(R.id.progress); avatarProgress = (ProgressBar) avatarPage.findViewById(R.id.progress); aboutScroll = (ScrollView) aboutPage.findViewById(R.id.scroll); homeScroll = (ScrollView) homePage.findViewById(R.id.scroll); workScroll = (ScrollView) workPage.findViewById(R.id.scroll); avatarScroll = (ScrollView) avatarPage.findViewById(R.id.scroll); list = (ListView) statusPage.findViewById(R.id.list); list.setDividerHeight(0); list.setCacheColorHint(0x00000000); aboutPage.setTag(getString(R.string.About)); homePage.setTag(getString(R.string.Home)); workPage.setTag(getString(R.string.Work)); avatarPage.setTag(getString(R.string.Photo)); statusPage.setTag(getString(R.string.Status)); ArrayList<View> mPages = new ArrayList<View>(); mPages.add(aboutPage); mPages.add(homePage); mPages.add(workPage); mPages.add(avatarPage); mPages.add(statusPage); MainPageAdapter adapter = new MainPageAdapter(mPages); ViewPager mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(adapter); mPager.setCurrentItem(0); TitlePageIndicator mTitleIndicator = (TitlePageIndicator) findViewById(R.id.indicator); mTitleIndicator.setTextColor(0xFF555555); mTitleIndicator.setViewPager(mPager); mTitleIndicator.setCurrentItem(0); new LoadTask().execute(); }
From source file:com.zzl.zl_app.cache.Utility.java
public static boolean loadFile(String loadpath, String fileName, String savePath, Context context, String broadcastAction) { FileOutputStream fos = null; // ? FileInputStream fis = null; // ? InputStream is = null; // ? HttpURLConnection httpConnection = null; int readLength = 0; // ?? int file_length = 0; URL url = null;// w ww.j a v a 2s . c o m try { url = new URL(loadpath); httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setConnectTimeout(10000); httpConnection.setRequestMethod("GET"); is = httpConnection.getInputStream(); FileTools.creatDir(savePath); String filePath = savePath + fileName; FileTools.deleteFile(filePath); FileTools.creatFile(filePath); File download_file = new File(filePath); fos = new FileOutputStream(download_file, true); // ?? fis = new FileInputStream(download_file); // ?? int total_read = fis.available(); // ??0 file_length = httpConnection.getContentLength(); // ? if (is == null) { // ? Tools.log("Voice", "donload failed..."); return false; } byte buf[] = new byte[3072]; // readLength = 0; // Tools.log("Voice", "download start..."); Intent startIntent = new Intent(); Bundle b = new Bundle(); if (broadcastAction != null) { // ????? b.putInt("fileSize", file_length); b.putInt("progress", 0); startIntent.putExtras(b); startIntent.setAction(broadcastAction); context.sendBroadcast(startIntent); } // ????? while (readLength != -1) { if ((readLength = is.read(buf)) > 0) { fos.write(buf, 0, readLength); total_read += readLength; // } if (broadcastAction != null) { b.putInt("fileSize", file_length); b.putInt("progress", total_read); startIntent.putExtras(b); startIntent.setAction(broadcastAction); context.sendBroadcast(startIntent); } if (total_read == file_length) { // ? Tools.log("Voice", "download complete..."); // ?????? if (broadcastAction != null) { Intent completeIntent = new Intent(); b.putBoolean("isFinish", true); completeIntent.putExtras(b); completeIntent.setAction(broadcastAction); context.sendBroadcast(completeIntent); } } // Thread.sleep(10); // ?10 } } catch (Exception e) { if (broadcastAction != null) { Intent errorIntent = new Intent(); errorIntent.setAction(broadcastAction); context.sendBroadcast(errorIntent); e.printStackTrace(); } } finally { try { if (fos != null) { fos.close(); } if (fis != null) { is.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return true; }
From source file:org.caboclo.clients.OneDriveClient.java
@Override public void putFile(File file, String path) throws IOException { final String BOUNDARY_STRING = "3i2ndDfv2rThIsIsPrOjEcTSYNceEMCPROTOTYPEfj3q2f"; //We use the directory name (without actual file name) to get folder ID int indDirName = path.replace("/", "\\").lastIndexOf("\\"); String targetFolderId = getFolderID(path.substring(0, indDirName)); System.out.printf("Put file: %s\tId: %s\n", path, targetFolderId); if (targetFolderId == null || targetFolderId.isEmpty()) { return;/*from w w w. j a v a2 s . c o m*/ } URL connectURL = new URL("https://apis.live.net/v5.0/" + targetFolderId + "/files?" + "state=MyNewFileState&redirect_uri=https://login.live.com/oauth20_desktop.srf" + "&access_token=" + accessToken); HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY_STRING); // set read & write conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); // set body DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes("--" + BOUNDARY_STRING + "\r\n"); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"\r\n"); dos.writeBytes("Content-Type: application/octet-stream\r\n"); dos.writeBytes("\r\n"); FileInputStream fileInputStream = new FileInputStream(file); int fileSize = fileInputStream.available(); int maxBufferSize = 8 * 1024; int bufferSize = Math.min(fileSize, maxBufferSize); byte[] buffer = new byte[bufferSize]; // send file int bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { // Upload file part(s) dos.write(buffer, 0, bytesRead); int bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, buffer.length); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } fileInputStream.close(); // send file end dos.writeBytes("\r\n"); dos.writeBytes("--" + BOUNDARY_STRING + "--\r\n"); dos.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; StringBuilder sbuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { sbuilder.append(line); } String fileId = null; try { JSONObject json = new JSONObject(sbuilder.toString()); fileId = json.getString("id"); //System.out.println("File ID is: " + fileId); //System.out.println("File name is: " + json.getString("name")); //System.out.println("File uploaded sucessfully."); } catch (JSONException e) { Logger.getLogger(OneDriveClient.class.getName()).log(Level.WARNING, "Error uploading file " + file.getName(), e); } }
From source file:org.tolven.security.password.PasswordHolder.java
private Passwords loadPasswords() { FileInputStream in = null; ByteArrayInputStream bais = null; try {/*from www. ja va 2 s . c om*/ try { Passwords passwords = null; if (getPasswordStoreFile().exists()) { in = new FileInputStream(getPasswordStoreFile()); byte[] encryptedPasswords = new byte[in.available()]; in.read(encryptedPasswords); Cipher cipher = Cipher.getInstance(getSecretKey().getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, getSecretKey()); byte[] decryptedPasswords = cipher.doFinal(encryptedPasswords); bais = new ByteArrayInputStream(decryptedPasswords); JAXBContext jc = JAXBContext.newInstance("org.tolven.security.password.bean", getClass().getClassLoader()); Unmarshaller unmarshaller = jc.createUnmarshaller(); passwords = (Passwords) unmarshaller.unmarshal(bais); } else { passwords = new ObjectFactory().createPasswords(); } return passwords; } finally { if (bais != null) bais.close(); if (in != null) in.close(); } } catch (Exception ex) { throw new RuntimeException("Could not load passwords from: " + getPasswordStoreFile()); } }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractLogoController.java
private void logoResponse(String imagePath, String defaultImagePath, HttpServletResponse response, String cssdkFilesDirectory) { FileInputStream fileinputstream = null; String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath); if (StringUtils.isNotBlank(cssdkFilesDirectory)) { rootImageDir = cssdkFilesDirectory; }/* w w w. ja v a2 s . c om*/ if (rootImageDir != null && !rootImageDir.trim().equals("")) { try { if (imagePath != null && !imagePath.trim().equals("")) { String absoluteImagePath = FilenameUtils.concat(rootImageDir, imagePath); fileinputstream = new FileInputStream(absoluteImagePath); if (fileinputstream != null) { int numberBytes = fileinputstream.available(); byte bytearray[] = new byte[numberBytes]; fileinputstream.read(bytearray); response.setContentType("image/" + FilenameUtils.getExtension(imagePath)); // TODO:Set Cache headers for browser to force browser to cache to reduce load OutputStream outputStream = response.getOutputStream(); response.setContentLength(numberBytes); outputStream.write(bytearray); outputStream.flush(); outputStream.close(); fileinputstream.close(); return; } } } catch (FileNotFoundException e) { logger.debug("###File not found in retrieving logo " + imagePath); } catch (IOException e) { logger.debug("###IO Error in retrieving logo"); } } response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", defaultImagePath); }
From source file:org.apache.hadoop.mapred.TestConcatenatedCompressedInput.java
/** * Test using the new BuiltInGzipDecompressor codec for reading gzip files. */// w w w .ja v a 2s . c o m // NOTE: This fails on RHEL4 with "java.io.IOException: header crc mismatch" // due to buggy version of zlib (1.2.1.2) included. @Test public void testBuiltInGzipDecompressor() throws IOException { JobConf jobConf = new JobConf(defaultConf); jobConf.setBoolean("io.native.lib.available", false); CompressionCodec gzip = new GzipCodec(); ReflectionUtils.setConf(gzip, jobConf); localFs.delete(workDir, true); assertEquals("[non-native (Java) codec]", org.apache.hadoop.io.compress.zlib.BuiltInGzipDecompressor.class, gzip.getDecompressorType()); System.out.println(COLOR_BR_YELLOW + "testBuiltInGzipDecompressor() using" + " non-native (Java Inflater) Decompressor (" + gzip.getDecompressorType() + ")" + COLOR_NORMAL); // copy single-member test file to HDFS String fn1 = "testConcatThenCompress.txt" + gzip.getDefaultExtension(); Path fnLocal1 = new Path(System.getProperty("test.concat.data", "/tmp"), fn1); Path fnHDFS1 = new Path(workDir, fn1); localFs.copyFromLocalFile(fnLocal1, fnHDFS1); // copy multiple-member test file to HDFS // (actually in "seekable gzip" format, a la JIRA PIG-42) String fn2 = "testCompressThenConcat.txt" + gzip.getDefaultExtension(); Path fnLocal2 = new Path(System.getProperty("test.concat.data", "/tmp"), fn2); Path fnHDFS2 = new Path(workDir, fn2); localFs.copyFromLocalFile(fnLocal2, fnHDFS2); FileInputFormat.setInputPaths(jobConf, workDir); // here's first pair of DecompressorStreams: final FileInputStream in1 = new FileInputStream(fnLocal1.toString()); final FileInputStream in2 = new FileInputStream(fnLocal2.toString()); assertEquals("concat bytes available", 2734, in1.available()); assertEquals("concat bytes available", 3413, in2.available()); // w/hdr CRC CompressionInputStream cin2 = gzip.createInputStream(in2); LineReader in = new LineReader(cin2); Text out = new Text(); int numBytes, totalBytes = 0, lineNum = 0; while ((numBytes = in.readLine(out)) > 0) { ++lineNum; totalBytes += numBytes; } in.close(); assertEquals("total uncompressed bytes in concatenated test file", 5346, totalBytes); assertEquals("total uncompressed lines in concatenated test file", 84, lineNum); // test BuiltInGzipDecompressor with lots of different input-buffer sizes doMultipleGzipBufferSizes(jobConf, false); // test GzipZlibDecompressor (native), just to be sure // (FIXME? could move this call to testGzip(), but would need filename // setup above) (alternatively, maybe just nuke testGzip() and extend this?) doMultipleGzipBufferSizes(jobConf, true); }
From source file:com.curso.listadapter.net.RESTClient.java
public void writeFile(DataOutputStream dos, String NameParamImage, File file) { //BEGIN THE UPLOAD Log.d("Test", "(********) BEGINS THE WRITTING"); if (file.exists()) { Log.d("Test", "(*****) FILE EXISTES"); } else {/* w w w .jav a 2 s . c o m*/ Log.d("Test", "(*****) FILE DOES NOT EXIST"); } try { FileInputStream fileInputStream; fileInputStream = new FileInputStream(file); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; Log.e("Test", "(*****) fileInputStream.available():" + fileInputStream.available()); post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\"" + file.getName() + "\"" + lineEnd; String mimetype = getMimeType(file.getName()); post += "Content-Type: " + mimetype + lineEnd; post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd; dos.writeBytes(post); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } fileInputStream.close(); post += lineEnd; post += twoHyphens + boundary + twoHyphens; Log.i("Test", "(********) WRITING FILE ENDED"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("Test", "(********) EXITING FROM FILE WRITTING"); }