public static FileInputStream resetInput(FileInputStream stream, File in, long toPoint) throws IOException { stream.close(); FileInputStream ret = new FileInputStream(in); ret.skip(toPoint); return ret; }
/** * Loads the bytes in a file. * * @param name the file name * @return an array with the bytes in the file */ public byte[] loadBytes(String name) throws IOException { FileInputStream in = null; in = new FileInputStream(name); try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int ch; while ((ch = in.read()) != -1) buffer.write(ch); return buffer.toByteArray(); } finally { in.close(); } }
public String readFile(java.io.File f) { StringBuffer buffer = new StringBuffer(); try { FileInputStream fis = new FileInputStream(f); InputStreamReader isr = new InputStreamReader(fis); int c; while ((c = isr.read()) != -1) buffer.append((char) c); isr.close(); fis.close(); } catch (Exception ex) { ex.printStackTrace(); } return buffer.toString(); }
public void loadSerializedData() { // fixme Race x = loadXML(); // return; // lastRace.getName(); // RaceRun run; try { // lastRace.loadSerializedData(); String fileName = lastRace.getName(); FileInputStream fileIn = new FileInputStream(fileName + ".ser"); // "RaceRun.ser"); try { ObjectInputStream in = new ObjectInputStream(fileIn); deSerialize(in); in.close(); fileIn.close(); tagHeuerConnected = new Boolean(false); // / make sure it exists - transient object microgateConnected = new Boolean(false); // / make sure it exists - transient object } catch (InvalidClassException ice) { log.info("Invalid Class from deserialization " + ice.classname); } catch (EOFException eof) { log.info("EOF on Serialized data"); } catch (IOException i) { i.printStackTrace(); // } catch (ClassNotFoundException cnf) { // cnf.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } catch (FileNotFoundException fnf) { // Empty block OK - ignore this exception } // load required transient members Log raceRunLog = Log.getInstance(); for (RaceRun r : activeRuns) { r.setLog(raceRunLog); } for (RaceRun r : completedRuns) { r.setLog(raceRunLog); } if (pendingRerun != null) { pendingRerun.setLog(raceRunLog); } // updateResults(); //todo OK Here ??? NO - didn't set }
// Function use to load all Records from File when Application Execute. void populateArray() { try { fis = new FileInputStream("Bank.dat"); dis = new DataInputStream(fis); // Loop to Populate the Array. while (true) { for (int i = 0; i < 6; i++) { records[rows][i] = dis.readUTF(); } rows++; } } catch (Exception ex) { total = rows; if (total == 0) { JOptionPane.showMessageDialog( null, "Records File is Empty.\nEnter Records First to Display.", "BankSystem - EmptyFile", JOptionPane.PLAIN_MESSAGE); btnEnable(); } else { try { dis.close(); fis.close(); } catch (Exception exp) { } } } }
public Class loadNewClass(String javaFile, String packageName) { Class myClass = null; String className = javaFile.replace(".java", ".class"); File inpFile = new File(className); int idx = className.lastIndexOf(File.separatorChar); String javaName = className.substring(idx + 1, className.indexOf(".")); int size = (int) inpFile.length(); byte[] ba = new byte[size]; try { FileInputStream fis = new FileInputStream(className); // read the entry int bytes_read = 0; while (bytes_read != size) { int r = fis.read(ba, bytes_read, size - bytes_read); if (r < 0) break; bytes_read += r; } if (bytes_read != size) throw new IOException("cannot read entry"); } catch (FileNotFoundException fnfExc) { System.out.println("File : " + className + " not found"); fnfExc.printStackTrace(); } catch (IOException ioExc) { System.out.println("IO Exception in JavaCompile trying to read class: "); ioExc.printStackTrace(); } try { String packageAppendedFileName = ""; if (packageName.isEmpty()) packageAppendedFileName = javaName; else packageAppendedFileName = packageName + "." + javaName; packageAppendedFileName.replace(File.separatorChar, '.'); myClass = defineClass(packageAppendedFileName, ba, 0, size); // SOS-StergAutoCompletionScalaSci.upDateAutoCompletion(myClass); String userClassName = myClass.getName(); JOptionPane.showMessageDialog(null, "Class " + userClassName + " loaded successfully !"); } catch (ClassFormatError exc) { System.out.println("error defining class " + inpFile); exc.printStackTrace(); } catch (Exception ex) { System.out.println("some error defining class " + inpFile); ex.printStackTrace(); } return myClass; }
protected byte[] getClassData(String directory, String name) { String classFile = directory + "/" + name.replace('.', '/') + ".class"; int classSize = (int) new File(classFile).length(); byte[] buf = new byte[classSize]; try { FileInputStream filein = new FileInputStream(classFile); classSize = filein.read(buf); filein.close(); } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } return buf; }
// read a jpeg file into a buffered image protected static Image loadJPG(String filename) { FileInputStream in = null; try { in = new FileInputStream(filename); } catch (java.io.FileNotFoundException io) { System.out.println("File Not Found"); } JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in); BufferedImage bi = null; try { bi = decoder.decodeAsBufferedImage(); in.close(); } catch (java.io.IOException io) { System.out.println("IOException"); } return bi; }
private void openBin() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(binFilter); fileChooser.setFileFilter(binFilter); if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { try { FileInputStream inbinf = new FileInputStream(fileChooser.getSelectedFile()); int len = inbinf.available(); if (len % 2 == 1) throw new IOException(String.format("Odd file size (0x%x)\n", len)); len /= 2; if (len > 0x10000) throw new IOException(String.format("Too large file (0x%x)\n", len)); binary = new char[len]; for (int i = 0; i < len; i++) { int lo = inbinf.read(); int hi = inbinf.read(); if (lo == -1 || hi == -1) throw new IOException("Unable to read\n"); binary[i] = (char) ((hi << 8) | lo); } asmMap = new AsmMap(); Disassembler dasm = new Disassembler(); dasm.init(binary); // TODO attach asmmap StringBuilder sb = new StringBuilder(); while (dasm.getAddress() < binary.length) { int addr = dasm.getAddress(); sb.append(String.format("%-26s ; [%04x] =", dasm.next(true), addr)); int addr2 = dasm.getAddress(); while (addr < addr2) { char i = binary[addr++]; sb.append( String.format(" %04x '%s'", (int) i, (i >= 0x20 && i < 0x7f) ? (char) i : '.')); } sb.append("\n"); } srcBreakpoints.clear(); sourceRowHeader.breakpointsChanged(); sourceTextarea.setText(sb.toString()); } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file: %s" + e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
private AsmCodeGenerator initCodeGenerator( final String formFileName, final String className, final String testDataPath) throws Exception { String tmpPath = FileUtil.getTempDirectory(); String formPath = testDataPath + formFileName; String javaPath = testDataPath + className + ".java"; final int rc = Main.compile(new String[] {"-d", tmpPath, javaPath}); assertEquals(0, rc); final String classPath = tmpPath + "/" + className + ".class"; final File classFile = new File(classPath); assertTrue(classFile.exists()); final LwRootContainer rootContainer = loadFormData(formPath); final AsmCodeGenerator codeGenerator = new AsmCodeGenerator( rootContainer, myClassFinder, myNestedFormLoader, false, new ClassWriter(ClassWriter.COMPUTE_FRAMES)); final FileInputStream classStream = new FileInputStream(classFile); try { codeGenerator.patchClass(classStream); } finally { classStream.close(); FileUtil.delete(classFile); final File[] inners = new File(tmpPath) .listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(className + "$") && name.endsWith(".class"); } }); if (inners != null) { for (File file : inners) FileUtil.delete(file); } } return codeGenerator; }
private void laden(Path saveName) throws IOException { Properties prop = new Properties(); FileInputStream in = new FileInputStream(saveName.toString()); prop.load(in); for (int i = 0; prop.containsKey(String.format("quellMenu%d", i)); i++) quellListModel.addElement( new ListItem( Paths.get(prop.getProperty(String.format("quellMenu%d", i))), Paths.get(prop.getProperty(String.format("quellMenu%d", i))))); for (int i = 0; prop.containsKey(String.format("zielMenu%d", i)); i++) zielListModel.addElement( new ListItem( Paths.get(prop.getProperty(String.format("zielMenu%d", i))), Paths.get(prop.getProperty(String.format("zielMenu%d", i))))); in.close(); }
private void openSrc() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(asmFilter); fileChooser.setFileFilter(asmFilter); if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { try { FileInputStream input = new FileInputStream(fileChooser.getSelectedFile()); char[] csources = new char[input.available()]; new InputStreamReader(input).read(csources, 0, csources.length); srcBreakpoints.clear(); sourceRowHeader.breakpointsChanged(); sourceTextarea.setText(new String(csources)); asmMap = new AsmMap(); binary = new char[0]; } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
public void openFile(String filename) { try { FileInputStream input = new FileInputStream(filename); char x; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { x = (char) input.read(); if (x == 'P') { puzzleBox[i][j].setText(String.valueOf((char) input.read())); puzzleBox[i][j].setEnabled(false); } else { x = (char) input.read(); if (x == 'X') { puzzleBox[i][j].setText(""); puzzleBox[i][j].setEnabled(true); } else { puzzleBox[i][j].setText(String.valueOf(x)); puzzleBox[i][j].setEnabled(true); } } } x = (char) input.read(); x = (char) input.read(); } input.close(); } catch (IOException ioException) { JOptionPane.showMessageDialog(this, "Error Opening File", "Error", JOptionPane.ERROR_MESSAGE); } }
public static void sendFile(Socket sock, File in, byte[] hash) throws IOException, NoSuchAlgorithmException { long len = in.length(); int block = 0; FileInputStream fis = new FileInputStream(in); while (block * BLOCK_SIZE < len) { // while the client is waiting for the file int blockSize = (int) Math.min(len - block * BLOCK_SIZE, BLOCK_SIZE); writeInteger(sock.getOutputStream(), blockSize); // send the size of this block byte[] minorHash = hashpipe(fis, sock.getOutputStream(), blockSize); // send the contents of the block if (hashMatch( sock.getInputStream(), minorHash)) { // read the client's minor hash, if the client's hash was correct writeInteger( sock.getOutputStream(), TRANS_SUCCESS); // tell the client it read everything correctly block++; // increment the block and keep reading } else { // if the client's hash was incorrect writeInteger( sock.getOutputStream(), TRANS_ERROR); // tell the client it misread that last block fis = resetInput( fis, in, block * BLOCK_SIZE); // reset the file reader to the start of the current block } if (block * BLOCK_SIZE >= len) { // if this is the last block writeInteger(sock.getOutputStream(), TRANS_FINISH); // send the end signal if (hashMatch( sock.getInputStream(), hash)) { // read the client's major hash, if the hash is correct fis.close(); // complete the transaction writeInteger(sock.getOutputStream(), TRANS_FINISH); } else { // if the hash is incorrect // ive no idea how we could have gotten to here writeInteger(sock.getOutputStream(), TRANS_RESTART); // send the restart signal block = 0; // set the block to be 0 fis = resetInput(fis, in, 0); // reset the file reader to the start of the current block } } } }
protected static boolean vnmrjPassword(String strUser, char[] password) { boolean blogin = false; try { PasswordService objPassword = PasswordService.getInstance(); String encrPassword = objPassword.encrypt(new String(password)); if (pwprops == null) { String strPath = FileUtil.openPath(WUserUtil.PASSWORD); if (strPath == null) return blogin; pwprops = new Properties(); FileInputStream fis = new FileInputStream(strPath); pwprops.load(fis); fis.close(); } String stoPassword = pwprops.getProperty(strUser); if (encrPassword.equals(stoPassword)) blogin = true; } catch (Exception e) { // e.printStackTrace(); Messages.writeStackTrace(e); } return blogin; }
/** Procedure to set value for the code-swap strings */ void getCodeSwapString() { File inputFile = new File(fileStr1); FileInputStream input = null; try { input = new FileInputStream(inputFile); } catch (FileNotFoundException fe) { System.err.println(fileStr1 + " not found. " + fe); // System.exit(-1);; } byte bt[] = new byte[(int) inputFile.length()]; try { input.read(bt); textStr1 = new String(bt); input.close(); } catch (IOException ie) { System.err.println("Can't read from the input stream " + ie); // System.exit(-1);; } inputFile = new File(fileStr2); try { input = new FileInputStream(inputFile); } catch (FileNotFoundException fe) { System.err.println(fileStr2 + " not found. " + fe); // System.exit(-1);; } try { bt = new byte[(int) inputFile.length()]; input.read(bt); textStr2 = new String(bt); input.close(); } catch (IOException ie) { System.err.println("Can't read from the input stream " + ie); // System.exit(-1);; } }
public static void main(String[] arg) { if (arg.length != 2) { System.err.println("usage: java ScpTo file1 user@remotehost:file2"); System.exit(-1); } FileInputStream fis = null; try { String lfile = arg[0]; String user = arg[1].substring(0, arg[1].indexOf('@')); arg[1] = arg[1].substring(arg[1].indexOf('@') + 1); String host = arg[1].substring(0, arg[1].indexOf(':')); String rfile = arg[1].substring(arg[1].indexOf(':') + 1); JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); session.connect(); boolean ptimestamp = true; // exec 'scp -t rfile' remotely String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); channel.connect(); if (checkAck(in) != 0) { System.exit(0); } File _lfile = new File(lfile); if (ptimestamp) { command = "T " + (_lfile.lastModified() / 1000) + " 0"; // The access time should be sent here, // but it is not accessible with JavaAPI ;-< command += (" " + (_lfile.lastModified() / 1000) + " 0\n"); out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { System.exit(0); } } // send "C0644 filesize filename", where filename should not include '/' long filesize = _lfile.length(); command = "C0644 " + filesize + " "; if (lfile.lastIndexOf('/') > 0) { command += lfile.substring(lfile.lastIndexOf('/') + 1); } else { command += lfile; } command += "\n"; out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { System.exit(0); } // send a content of lfile fis = new FileInputStream(lfile); byte[] buf = new byte[1024]; while (true) { int len = fis.read(buf, 0, buf.length); if (len <= 0) break; out.write(buf, 0, len); // out.flush(); } fis.close(); fis = null; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); if (checkAck(in) != 0) { System.exit(0); } out.close(); channel.disconnect(); session.disconnect(); System.exit(0); } catch (Exception e) { System.out.println(e); try { if (fis != null) fis.close(); } catch (Exception ee) { } } }
public void runEvaluator() { int nSize = r.getNodeCount(); nodeValues = new Double[nSize]; allValues = new Double[nSize][]; for (int i = 0; i < nSize; i++) { allValues[i] = new Double[nSize]; } // get Oj's double[] o = new double[nSize]; if (orgFile == null) { for (int i = 0; i < nSize; i++) { o[i] = 1.0; } } else { try { FileInputStream fis = new FileInputStream(orgFile); InputStreamReader isr = new InputStreamReader(fis); BufferedReader in = new BufferedReader(isr, 8096); String line = in.readLine(); // try to guess delimiters String delim = " "; if (line.indexOf('\t') != 0) { delim = "\t"; } else if (line.indexOf(',') != 0) { delim = ","; } Hashtable values = new Hashtable(); while (line != null) { StringTokenizer st = new StringTokenizer(line, delim); line = in.readLine(); String key = st.nextToken().trim(); if (st.hasMoreTokens()) { try { Double d = Double.valueOf(st.nextToken()); values.put(key, d); } catch (NumberFormatException nfe) { // ignore? } } } fis.close(); TreeSet missingActors = new TreeSet(); for (int i = 0; i < nSize; i++) { String actorName = r.getParent().getActor(i).getName(); Double oValue = (Double) values.get(actorName); if (oValue == null) { missingActors.add(actorName); o[i] = 1.0; } else { o[i] = oValue.doubleValue(); } } if (missingActors.size() > 0) { String errorMsg = "Couldn't find organization values for "; if (missingActors.size() <= 10) { Iterator iter = missingActors.iterator(); errorMsg += "'" + iter.next() + "'"; while (iter.hasNext()) { errorMsg += ", '" + iter.next() + "'"; } errorMsg += "."; } else { errorMsg += missingActors.size() + " actors."; } JFrame f = new JFrame(); JOptionPane.showMessageDialog( f, errorMsg, "Missing Values", JOptionPane.WARNING_MESSAGE); } } catch (IOException ioe) { Application.handleNonFatalThrowable(ioe); } } // i think i need to calculate all p_ij's double[][] p = new double[nSize][]; for (int i = 0; i < nSize; i++) { p[i] = new double[nSize]; double i_out = 0.0; for (int j = 0; j < nSize; j++) { if ((i != j) || (!ignoreDiagonals)) { if (investments == OUTBOUND || investments == BOTH) { i_out += r.getTieStrength(i, j); } if (investments == INBOUND || investments == BOTH) { i_out += r.getTieStrength(j, i); } } } for (int j = 0; j < nSize; j++) { p[i][j] = 0.0; if (i_out != 0.0) { if (investments == OUTBOUND || investments == BOTH) { p[i][j] += r.getTieStrength(i, j) / i_out; } if (investments == INBOUND || investments == BOTH) { p[i][j] += r.getTieStrength(j, i) / i_out; } } } } switch (type) { // implementation of Burt (1992: 64) equation 2.7 case CONSTRAINT: for (int i = 0; i < nSize; i++) { double i_total = 0.0; allValues[i][i] = new Double(Double.NaN); for (int j = 0; j < nSize; j++) { if (i != j) { double c_sum = p[i][j]; for (int q = 0; q < nSize; q++) { if ((q != i) && (q != j)) { c_sum += p[i][q] * p[q][j]; } } double c_ij = c_sum * c_sum * o[j]; i_total += c_ij; allValues[i][j] = new Double(c_ij); } } nodeValues[i] = new Double(i_total); } break; case EFFECTIVE_SIZE: break; } }
public void actionPerformed(ActionEvent e) { if (e.getSource() == jbSaveLayer) { try { FileOutputStream fout = new FileOutputStream(jtfCengMing.getText() + ".wyf"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(itemArray); oout.close(); fout.close(); } catch (Exception ea) { ea.printStackTrace(); } } else if (e.getSource() == jbLoadLayer) { try { FileInputStream fin = new FileInputStream(jtfCengMing.getText() + ".wyf"); ObjectInputStream oin = new ObjectInputStream(fin); itemArray = (Item[][]) oin.readObject(); oin.close(); fin.close(); this.flush(); } catch (Exception ea) { ea.printStackTrace(); } lvp.repaint(); } else if (e.getSource() == jbLoadAll) { // 全部铺上当前选中 for (int row = 0; row < 40; row++) { for (int col = 0; col < 60; col++) { Item item = ((Item) (jl.getSelectedValue())).clone(); itemArray[row][col] = item; if (item != null) { item.setPosition(col, row); } } } lvp.repaint(); } else if (e.getSource() == jbCreate) { // 生成源代码 try { FileOutputStream fout = null; DataOutputStream dout = null; fout = new FileOutputStream("maps.so"); dout = new DataOutputStream(fout); int totalBlocks = 0; for (int i = 0; i < 40; i++) { for (int j = 0; j < 60; j++) { Item item = itemArray[i][j]; if (item != null) { totalBlocks++; } } } System.out.println("totalBlocks=" + totalBlocks); // 写入不空块的数量 dout.writeInt(totalBlocks); for (int i = 0; i < 40; i++) { for (int j = 0; j < 60; j++) { Item item = itemArray[i][j]; if (item != null) { int w = item.w; // 元素的图片宽度 int h = item.h; // 元素的图片高度 int col = item.col; // 元素的地图列 int row = item.row; // 元素的地图行 int pCol = item.pCol; // 元素的占位列 int pRow = item.pRow; // 元素的占位行 String leiMing = item.leiMing; // 类名 int[][] notIn = item.notIn; // 不可通过 int[][] keYu = item.keYu; // 可遇矩阵 // 计算图片下标 int outBitmapInxex = 0; if (leiMing.equals("Grass")) { outBitmapInxex = 0; } else if (leiMing.equals("XiaoHua1")) { outBitmapInxex = 1; } else if (leiMing.equals("MuZhuang")) { outBitmapInxex = 2; } else if (leiMing.equals("XiaoHua2")) { outBitmapInxex = 3; } else if (leiMing.equals("Road")) { outBitmapInxex = 4; } else if (leiMing.equals("Jing")) { outBitmapInxex = 5; } dout.writeByte(outBitmapInxex); // 记录图片下标 dout.writeByte(0); // 记录可遇标志 0-不可遇 底层都不可遇 dout.writeByte(w); // 图片宽度 dout.writeByte(h); // 图片高度 dout.writeByte(col); // 总列数 dout.writeByte(row); // 总行数 dout.writeByte(pCol); // 占位列 dout.writeByte(pRow); // 占位行 int bktgCount = notIn.length; // 不可通过点的数量 dout.writeByte(bktgCount); // 写入不可通过点的数量 for (int k = 0; k < bktgCount; k++) { dout.writeByte(notIn[k][0]); dout.writeByte(notIn[k][1]); } } } } dout.close(); fout.close(); } catch (Exception ea) { ea.printStackTrace(); } } }