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(); }
/** * A convenience for {@link #openRead()} that also reads all of the file contents into a byte * array which is returned. */ public byte[] readFully() throws IOException { FileInputStream stream = openRead(); try { int pos = 0; int avail = stream.available(); byte[] data = new byte[avail]; while (true) { int amt = stream.read(data, pos, data.length - pos); // Log.i("foo", "Read " + amt + " bytes at " + pos // + " of avail " + data.length); if (amt <= 0) { // Log.i("foo", "**** FINISHED READING: pos=" + pos // + " len=" + data.length); return data; } pos += amt; avail = stream.available(); if (avail > data.length - pos) { byte[] newData = new byte[pos + avail]; System.arraycopy(data, 0, newData, 0, pos); data = newData; } } } finally { stream.close(); } }
private byte[] readFully() { int i = 0; if (mBackupName.exists()) { mBaseName.delete(); mBackupName.renameTo(mBaseName); } FileInputStream localFileInputStream = new FileInputStream(mBaseName); try { Object localObject1 = new byte[localFileInputStream.available()]; int j = localFileInputStream.read((byte[]) localObject1, i, localObject1.length - i); if (j <= 0) { return (byte[]) localObject1; } i = j + i; j = localFileInputStream.available(); if (j > localObject1.length - i) { byte[] arrayOfByte = new byte[j + i]; System.arraycopy(localObject1, 0, arrayOfByte, 0, i); localObject1 = arrayOfByte; } for (; ; ) { break; } } finally { localFileInputStream.close(); } }
private String readFile(File file) { byte[] reader = null; FileInputStream fis = null; if (DEBUG) Log.d(TAG, "loadFile : " + file.getPath()); if (file.exists()) { try { fis = new FileInputStream(file); reader = new byte[fis.available()]; if (DEBUG) Log.d(TAG, "fis.available " + fis.available()); while (fis.read(reader) != -1 && fis.available() > 0) {} } catch (IOException e) { Log.e(TAG, "loadFile error"); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } } } else { Log.w(TAG, "loadFile file is not existed"); } if (reader != null) { return new String(reader); } else { if (DEBUG) Log.d(TAG, "loadFile returned null"); return null; } }
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(); }
private void loadNextBlock() { while (true) { try { if (!fileIt.hasNext() && (currentFileStream == null || currentFileStream.available() < 1)) break; } catch (IOException e) { currentFileStream = null; if (!fileIt.hasNext()) break; } while (true) { try { if (currentFileStream != null && currentFileStream.available() > 0) break; } catch (IOException e1) { currentFileStream = null; } if (!fileIt.hasNext()) { nextBlock = null; currentFileStream = null; return; } try { currentFileStream = new FileInputStream(fileIt.next()); } catch (FileNotFoundException e) { currentFileStream = null; } } try { int nextChar = currentFileStream.read(); while (nextChar != -1) { if (nextChar != ((params.getPacketMagic() >>> 24) & 0xff)) { nextChar = currentFileStream.read(); continue; } nextChar = currentFileStream.read(); if (nextChar != ((params.getPacketMagic() >>> 16) & 0xff)) continue; nextChar = currentFileStream.read(); if (nextChar != ((params.getPacketMagic() >>> 8) & 0xff)) continue; nextChar = currentFileStream.read(); if (nextChar == (params.getPacketMagic() & 0xff)) break; } byte[] bytes = new byte[4]; currentFileStream.read(bytes, 0, 4); long size = Utils.readUint32BE(Utils.reverseBytes(bytes), 0); // We allow larger than MAX_BLOCK_SIZE because test code uses this as well. if (size > Block.MAX_BLOCK_SIZE * 2 || size <= 0) continue; bytes = new byte[(int) size]; currentFileStream.read(bytes, 0, (int) size); try { nextBlock = new Block(params, bytes); } catch (ProtocolException e) { nextBlock = null; continue; } break; } catch (IOException e) { currentFileStream = null; continue; } } }
public void uploadFile() throws IOException { String fileName = url.path().toString(); DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; FileInputStream fileInputStream = new FileInputStream(fileName); // Open a HTTP connection to the URL request = (HttpURLConnection) url.getUrl().openConnection(); request.setDoInput(true); // Allow Inputs request.setDoOutput(true); // Allow Outputs request.setUseCaches(false); // Don't use a Cached Copy request.setChunkedStreamingMode(1024); request.setRequestMethod("POST"); request.setRequestProperty("requestection", "Keep-Alive"); request.setRequestProperty("ENCTYPE", "multipart/form-data"); request.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); request.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(request.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes( "Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... 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); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // close the streams // fileInputStream.close(); dos.flush(); dos.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) { } ; } }
public static void main(String[] args) throws Exception { FileInputStream reader = new FileInputStream(args[0]); int all = reader.available(); int spacesCount = 0; while (reader.available() > 0) { if ((char) reader.read() == ' ') spacesCount++; } double d = (double) spacesCount / all * 100; d = new BigDecimal(d).setScale(2, RoundingMode.HALF_UP).doubleValue(); System.out.println(d); reader.close(); }
/** * 上传文件 * * @param file 文件路径(包含文件名) * @param File _file 文件描述符 return true or false */ public boolean writeFile(String file, File _file, Boolean auto) throws Exception { FileInputStream is = new FileInputStream(_file); String result = ""; try { URL url = new URL("http://" + api_domain + "/" + bucketname + file); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(timeout); conn.setRequestMethod("PUT"); conn.setUseCaches(false); conn.setRequestProperty("Date", getGMTDate()); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", is.available() + ""); if (this.content_md5 != null) conn.setRequestProperty("Content-Md5", this.content_md5); if (this.file_secret != null) conn.setRequestProperty("Content-Secret", this.file_secret); conn.setRequestProperty("Authorization", sign(conn, "/" + bucketname + file, is.available())); if (auto) conn.setRequestProperty("mkdir", "true"); this.content_md5 = null; this.file_secret = null; try { conn.connect(); OutputStream os = conn.getOutputStream(); byte[] data = new byte[4096]; int wl = 0; try { int temp = 0; while ((temp = is.read(data)) != -1) { os.write(data, 0, temp); } } finally { os.flush(); if (os != null) { os.close(); } } result = getText(conn, false); } finally { is.close(); if (conn != null) { conn.disconnect(); conn = null; } } return true; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } finally { is.close(); } }
public void test_available() throws IOException { is = new FileInputStream(fileName); assertEquals( "Test 1: Returned incorrect number of available bytes;", fileString.length(), is.available()); is.close(); try { is.available(); fail("Test 2: IOException expected."); } catch (IOException e) { // Expected. } }
/** * @param file 文件 * @param fileName 文件名 * @return 返回Null则为失败 */ public static String uploadFile(File file, String fileName) { FileInputStream fis = null; try { NameValuePair[] meta_list = null; // new NameValuePair[0]; fis = new FileInputStream(file); byte[] file_buff = null; if (fis != null) { int len = fis.available(); file_buff = new byte[len]; fis.read(file_buff); } String fileid = storageClient1.upload_file1(file_buff, getFileExt(fileName), meta_list); return fileid; } catch (Exception ex) { logger.error(ex); return null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { logger.error(e); } } } }
/** * @param bytes * @param filename * @param action * @throws IOException */ public static void bytes2file(byte[] bytes, String filename, int action) throws IOException { File file; byte[] data; switch (action) { case OVERWRITE: file = new File(filename); if (file.exists()) { file.delete(); } bytes2file(filename, bytes); break; case APPEND: file = new File(filename); if (file.exists()) { FileInputStream fileInputStream = new FileInputStream(file); int length = fileInputStream.available(); data = new byte[length]; fileInputStream.read(data); data = ByteUtil.merge(data, bytes); fileInputStream.close(); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(data); fileOutputStream.flush(); fileOutputStream.close(); } break; default: bytes2file(bytes, filename, OVERWRITE); } }
private byte[] loadClassData(File f) throws ClassNotFoundException { FileInputStream stream = null; try { // System.out.println("loading: "+f.getPath()); stream = new FileInputStream(f); try { byte[] b = new byte[stream.available()]; stream.read(b); return b; } catch (IOException e) { throw new ClassNotFoundException(); } } catch (FileNotFoundException e) { throw new ClassNotFoundException(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { /* ignore */ } } } }
public static void add(File f, String name, JarOutputStream jos) throws IOException { String en = name; if (f.isDirectory()) en += "/"; JarEntry entry = (en.endsWith("/")) ? null : new JarEntry(en); if (f.isDirectory()) { if ("/".equals(en)) en = ""; File[] fs = f.listFiles(); if (fs != null) for (int i = 0; i < fs.length; i++) add(fs[i], en + fs[i].getName(), jos); } else { try { jos.putNextEntry(entry); } catch (IOException e) { return; } FileInputStream is = new FileInputStream(f); byte[] b = new byte[1024]; int q = 0; while ((q = is.available()) > 0) { if (q > 1024) q = 1024; q = is.read(b, 0, q); jos.write(b, 0, q); } is.close(); } if (entry != null) jos.closeEntry(); }
public static Texture getTextureFromPath(String path) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { if (textures.containsKey(path)) { return textures.get(path); } Texture texture = null; try { FileInputStream stream = new FileInputStream(path); if (stream.available() > 0) { texture = TextureLoader.getTexture("PNG", stream, true, GL11.GL_NEAREST); } stream.close(); } catch (IOException e) { } if (texture != null) { textures.put(path, texture); } return texture; } finally { SpoutClient.enableSandbox(wasSandboxed); } }
/* * 返回图片 */ @RequestMapping(value = "/images/{name:.+}", method = RequestMethod.GET) @ResponseBody public void getPic(@PathVariable String name, HttpServletResponse resp) throws IOException { if (null == name) { return; } String path = ImageUtil.ImageRoot + "/"; FileInputStream fis = new FileInputStream(path + name); int size = fis.available(); // 得到文件大小 byte data[] = new byte[size]; fis.read(data); // 读数据 fis.close(); resp.setContentType("image/gif"); OutputStream os = resp.getOutputStream(); os.write(data); os.flush(); os.close(); }
private String getFileContent(final File file) { FileInputStream fileInputStream; try { fileInputStream = new FileInputStream(file); StringBuilder sb = null; while (fileInputStream.available() > 0) { sb = new StringBuilder(); sb.append((char) fileInputStream.read()); } String fileContent = null; if (null != sb) { fileContent = sb.toString(); } fileInputStream.close(); return fileContent; } catch (FileNotFoundException e) { } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
/** * It will call the external dot program, and return the image in binary format. * * @param dot Source of the graph (in dot language). * @return The image of the graph in .gif format. */ private byte[] get_img_stream(File dot) { File img; byte[] img_stream = null; try { img = File.createTempFile("graph_", ".gif", new File(this.TEMP_DIR)); String temp = img.getAbsolutePath(); Runtime rt = Runtime.getRuntime(); String cmd = DOT + " -Tgif " + dot.getAbsolutePath() + " -o" + img.getAbsolutePath(); Process p = rt.exec(cmd); p.waitFor(); FileInputStream in = new FileInputStream(img.getAbsolutePath()); img_stream = new byte[in.available()]; in.read(img_stream); // Close it if we need to if (in != null) in.close(); if (img.delete() == false) System.err.println("Warning: " + img.getAbsolutePath() + " could not be deleted!"); } catch (java.io.IOException ioe) { System.err.println("Error: in I/O processing of tempfile in dir " + this.TEMP_DIR + "\n"); System.err.println(" or in calling external command"); ioe.printStackTrace(); } catch (java.lang.InterruptedException ie) { System.err.println("Error: the execution of the external program was interrupted"); ie.printStackTrace(); } return img_stream; }
public ArrayList<FIncomePO> findbyHall(String hall) throws RemoteException, IOException { ArrayList<FIncomePO> income = new ArrayList<FIncomePO>(); ObjectInputStream os = null; System.out.println("start find!"); try { FileInputStream fs = new FileInputStream(file); os = new ObjectInputStream(fs); FIncomePO po = (FIncomePO) os.readObject(); while (fs.available() > 0) { byte[] buf = new byte[4]; fs.read(buf); FIncomePO incomepo = (FIncomePO) os.readObject(); if (incomepo.getShop().equals(hall)) { income.add(incomepo); } } return income; } catch (Exception e) { return null; } finally { os.close(); } }
public String readfile(String path, String filename) { File f = new File(path + filename); if (!f.exists()) { Log.v("filecheck", filename + "not exist"); savefile(path, filename, "NULL"); } StringBuffer sb = new StringBuffer(); Log.v("fileWriter", filename + " reading started"); try { FileInputStream fis = new FileInputStream(path + filename); int n; while ((n = fis.available()) > 0) { byte b[] = new byte[n]; if (fis.read(b) == -1) break; sb.append(new String(b)); } fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); System.err.println("Could not find file" + filename); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); }
public Logger(String name) { this.name = name; String tmp = CrashFileHelper.dateToString(new Date()); File logFile = new File( System.getProperty("user.dir") + "/log/", name + tmp.substring(0, tmp.lastIndexOf("_")) + ".log"); try { byte[] buf = null; int av = 0; if (!logFile.exists()) { logFile.getParentFile().mkdirs(); logFile.createNewFile(); } else { FileInputStream fis = new FileInputStream(logFile); buf = new byte[fis.available()]; av = fis.read(buf); fis.close(); } this.log = new FileOutputStream(logFile); if (buf != null) this.log.write(buf, 0, av); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) sb.append('='); print(sb.toString()); } catch (Exception e) { e.printStackTrace(); System.out.println("Ошибка инициализации системы логирования"); } }
private void kill_pcscd() { File f = new File(ctx.getFilesDir() + "/pcscd/pcscd.pid"); FileInputStream fis = null; if (f.exists()) { try { // read pid fis = new FileInputStream(f); byte[] pid = new byte[fis.available()]; int num = fis.read(pid); if (num > 0) { // kill pcsc daemon ProcessBuilder pb = new ProcessBuilder("kill", "-9", new String(pid, "UTF-8")); pb.start(); } // cleanup files String del = ctx.getFilesDir() + "/pcscd/*"; ProcessBuilder pb = new ProcessBuilder("rm", "-r", del); pb.start(); } catch (IOException e) { logger.error("Killing the pcsc daemon or cleanup failed.", e); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { // ignore } } } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); SharedPreferences mySharedPreference = getSharedPreferences("filesMTime", Activity.MODE_PRIVATE); SharedPreferences mySharedPreference2 = getSharedPreferences("filesATime", Activity.MODE_PRIVATE); setTitle("Notepad"); String title = this.getIntent().getStringExtra("Name"); showpanel = (TextView) findViewById(R.id.textView); showpanel.setTextSize(5.0f); showpanel.setTextColor(Color.BLUE); showpanel.append("创建时间:" + mySharedPreference2.getString(title, "") + "\n"); showpanel.append("最后修改时间:" + mySharedPreference.getString(title, "") + "\n\n"); showpanel.setTextSize(20.0f); showpanel.setTextColor(Color.BLACK); showpanel.append(title + ":\n"); try { FileInputStream ins = openFileInput(title); byte[] buffer = new byte[ins.available()]; ins.read(buffer); showpanel.append(new String(buffer)); ins.close(); } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } }
public static String readJsonFile(String filePath) { File file = new File(filePath); if (!file.exists()) { return null; } try { FileInputStream is = new FileInputStream(file); ; int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String jsonstr = new String(buffer, "UTF-8"); return jsonstr; } catch (Exception e) { e.printStackTrace(); } return null; }
@Before public void setUp() throws Exception { jmxNodeInfo = new JMXNodeInfo(0); jmxCollector = new JMXCollectorImpl(); platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName("org.opennms.netmgt.collectd.jmxhelper:type=JmxTest"); JmxTestMBean testMBean = new JmxTest(); platformMBeanServer.registerMBean(testMBean, objectName); collectionAgent = EasyMock.createMock(CollectionAgent.class); EasyMock.expect(collectionAgent.getAddress()).andReturn(InetAddress.getLocalHost()).anyTimes(); EasyMock.expect( collectionAgent.getAttribute("org.opennms.netmgt.collectd.JMXCollector.nodeInfo")) .andReturn(jmxNodeInfo) .anyTimes(); EasyMock.expect(collectionAgent.getNodeId()).andReturn(0).anyTimes(); EasyMock.expect(collectionAgent.getStorageDir()).andReturn(new File("")).anyTimes(); EasyMock.replay(collectionAgent); FileInputStream configFileStream = new FileInputStream("src/test/resources/etc/JmxCollectorConfigTest.xml"); logger.debug("ConfigFileStream check '{}'", configFileStream.available()); jmxConfigFactory = new JMXDataCollectionConfigFactory(configFileStream); JMXDataCollectionConfigFactory.setInstance(jmxConfigFactory); }
public ArrayList<FIncomePO> findByTime(String time1, String time2) throws RemoteException, IOException { ArrayList<FIncomePO> income = new ArrayList<FIncomePO>(); ObjectInputStream os = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); try { Date date1 = formatter.parse(time1); Date date2 = formatter.parse(time2); FileInputStream fs = new FileInputStream(file); os = new ObjectInputStream(fs); FIncomePO po = (FIncomePO) os.readObject(); while (fs.available() > 0) { byte[] buf = new byte[4]; fs.read(buf); FIncomePO incomepo = (FIncomePO) os.readObject(); if (formatter.parse(incomepo.getTime()).after(date1) && formatter.parse(incomepo.getTime()).before(date2)) { income.add(incomepo); } } return income; } catch (Exception e) { return null; } finally { os.close(); } }
/** * 以流的形式输出图片 * * @param httpServletResponse * @param imgPath */ public void writeImg(HttpServletResponse httpServletResponse, String imgPath) { FileInputStream fis = null; File file = null; httpServletResponse.setContentType("image/gif"); try { OutputStream out = httpServletResponse.getOutputStream(); file = new File( new File(this.getClass().getResource("/").getPath()).getParentFile().getParent() + imgPath); fis = new FileInputStream(file); byte[] b = new byte[fis.available()]; fis.read(b); out.write(b); // 以流的形式写出 out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (file != null && file.exists()) { // 删除临时文件 file.delete(); } } }
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 ArrayList<FIncomePO> findAll() throws RemoteException { ArrayList<FIncomePO> incomeList = new ArrayList<FIncomePO>(); FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); FIncomePO in = (FIncomePO) ois.readObject(); while (fis.available() > 0) { byte[] buf = new byte[4]; fis.read(buf); FIncomePO incomepo = (FIncomePO) ois.readObject(); incomeList.add(incomepo); } } catch (Exception e) { e.printStackTrace(); } finally { try { ois.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } return incomeList; }