private static void testSysOut(String fs, String exp, Object... args) { FileOutputStream fos = null; FileInputStream fis = null; try { PrintStream saveOut = System.out; fos = new FileOutputStream("testSysOut"); System.setOut(new PrintStream(fos)); System.out.format(Locale.US, fs, args); fos.close(); fis = new FileInputStream("testSysOut"); byte[] ba = new byte[exp.length()]; int len = fis.read(ba); String got = new String(ba); if (len != ba.length) fail(fs, exp, got); ck(fs, exp, got); System.setOut(saveOut); } catch (FileNotFoundException ex) { fail(fs, ex.getClass()); } catch (IOException ex) { fail(fs, ex.getClass()); } finally { try { if (fos != null) fos.close(); if (fis != null) fis.close(); } catch (IOException ex) { fail(fs, ex.getClass()); } } }
/** * Load the database from the database file given in "database.json" if the file doesn't exist, it * gets created here if the file has a database in it already, it is loaded here * * @return false if there is an error opening the database */ public boolean open() { try { System.out.println(dbPath); File dbFile = new File(dbPath); // Only read the database from the file if it exists if (dbFile.exists()) { FileInputStream fileIn = new FileInputStream(dbPath); ObjectInputStream in = new ObjectInputStream(fileIn); // load the database here database = (HashMap<K, V>) in.readObject(); // make sure the streams close properly in.close(); fileIn.close(); Debug.println("Database loaded"); } else { dbFile.getParentFile().mkdirs(); dbFile.createNewFile(); Debug.println("Database created"); } return true; } catch (Exception e) { System.err.println("Error opening database"); System.err.println(e); return false; } }
public static TaggedDictionary loadFrom(File f) throws Exception { FileInputStream fi = null; BufferedInputStream bi = null; ObjectInputStream oin = null; TaggedDictionary result = null; try { fi = new FileInputStream(f); bi = new BufferedInputStream(fi, 1000000); oin = new ObjectInputStream(bi); result = new TaggedDictionary(); result.readFrom(oin); } finally { try { oin.close(); } catch (Exception exx) { } try { bi.close(); } catch (Exception exx) { } try { fi.close(); } catch (Exception exx) { } } return result; }
private void sendFile(String filePath) { try { File fileToSend = new File(filePath); FileInputStream fileInputStream = new FileInputStream(fileToSend); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); OutputStream outputStream = clientSocket.getOutputStream(); // Writer: byte[] writerBuffer = new byte[(int) fileToSend.length()]; bufferedInputStream.read(writerBuffer, 0, writerBuffer.length); System.out.println("Sending " + filePath + "(" + writerBuffer.length + " bytes)"); outputStream.write("HTTP/1.1 200 OK\r\n\r\n".getBytes()); // System.out.println("Writing: "+new String(writerBuffer)); outputStream.write(writerBuffer, 0, writerBuffer.length); outputStream.flush(); System.out.println("Done."); // inputStream.close(); fileInputStream.close(); bufferedInputStream.close(); outputStream.close(); } catch (IOException e) { // report exception somewhere. e.printStackTrace(); } }
/** * @param superClass * @param classloader * @param classes * @param packagePath * @throws FileNotFoundException * @throws IOException */ private static void enumerateCompressedPackage( String prefix, Class superClass, ClassLoader classloader, LinkedList<Class> classes, File packagePath) throws FileNotFoundException, IOException { FileInputStream fileinputstream = new FileInputStream(packagePath); ZipInputStream zipinputstream = new ZipInputStream(fileinputstream); ZipEntry zipentry = null; do { zipentry = zipinputstream.getNextEntry(); if (zipentry != null && zipentry.getName().endsWith(".class")) { String classFileName = zipentry.getName(); String className = classFileName.lastIndexOf('/') > -1 ? classFileName.substring(classFileName.lastIndexOf('/') + 1) : classFileName; if (prefix == null || className.startsWith(prefix)) { try { String fullClassName = classFileName.substring(0, classFileName.length() - 6).replaceAll("/", "."); checkAndAddClass(classloader, superClass, classes, fullClassName); } catch (Exception ex) { } } } } while (zipentry != null); fileinputstream.close(); }
/** * The read admin list reads in admin objects from a readfile * * @return * @throws FileNotFoundException */ public LinkedList<Admin> readAdminList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("adminList.csv"); LinkedList<Admin> adminList = new LinkedList<Admin>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates admin Admin newAdmin = new Admin(userName, password, email, firstName, lastName, office, phoneNumber); adminList.add(newAdmin); } fstream.close(); } catch (Exception e) { adminList = null; } Collections.sort(adminList); return adminList; }
public void load() { if (!modelExists()) { loadError = "Cannot find " + LEVELS_DAT_FILE + "."; return; } File folder = new File(location); File dat = new File(folder, LEVELS_DAT_FILE); // File lst = new File(folder, LEVELS_LST_FILE); if (!dat.isFile()) return; ArrayList levels = new ArrayList(); try { FileInputStream reader = new FileInputStream(dat); long fileLength = dat.length(); int length = model.getField().getSize() + 96; int readLength = 0; byte[] buffer = new byte[length]; while (fileLength - readLength >= length) { int toRead = length; while (toRead > 0) { toRead -= reader.read(buffer, length - toRead, toRead); } readLength += length; SupaplexLevel level = new SupaplexLevel(); level.setModel(model); level.loadFromBytes(buffer); levels.add(level); } reader.close(); } catch (Exception e) { e.printStackTrace(); } SupaplexLevel[] ls = (SupaplexLevel[]) levels.toArray(new SupaplexLevel[0]); model.setLevels(ls); }
// Merge the availableChunks to build the original file void MergeChunks(File[] chunks) throws IOException { // Safety check if (chunks == null) { System.err.println("ERROR: No chunks to merge!"); return; } FileOutputStream fos = new FileOutputStream("complete/" + filename); try { FileInputStream fis; byte[] fileBytes; int bytesRead; for (File f : chunks) { fis = new FileInputStream(f); fileBytes = new byte[(int) f.length()]; bytesRead = fis.read(fileBytes, 0, (int) f.length()); assert (bytesRead == fileBytes.length); assert (bytesRead == (int) f.length()); fos.write(fileBytes); fos.flush(); fileBytes = null; fis.close(); fis = null; } } catch (Exception exception) { exception.printStackTrace(); } finally { fos.close(); fos = null; } }
public boolean load() { try { if (new File(FILE_PATH).exists()) { FileInputStream FIS = new FileInputStream(FILE_PATH); JXMLBaseObject cobjXmlObj = new JXMLBaseObject(); cobjXmlObj.InitXMLStream(FIS); FIS.close(); Vector exps = new Vector(); Element rootElmt = cobjXmlObj.GetElementByName(JCStoreTableModel.ROOT_NAME); for (Iterator i = rootElmt.getChildren().iterator(); i.hasNext(); ) { Element crtElmt = (Element) i.next(); JCExpression exp = new JCExpression(); exp.mId = crtElmt.getAttributeValue("id", ""); exp.mName = crtElmt.getAttributeValue("name", ""); exp.mShowValue = crtElmt.getAttributeValue("show", ""); exp.mStoreValue = crtElmt.getAttributeValue("store", ""); exps.add(exp); } if (mModel != null) { mModel.setExpression(exps); } } } catch (Exception e) { e.printStackTrace(); return false; } return true; }
public static WordClass[] loadWordClassesFrom(File f) throws Exception { FileInputStream fi = null; BufferedInputStream bi = null; ObjectInputStream oin = null; WordClass result[]; try { fi = new FileInputStream(f); bi = new BufferedInputStream(fi, 1000000); oin = new ObjectInputStream(bi); result = (WordClass[]) oin.readObject(); } finally { try { oin.close(); } catch (Exception exx) { } try { bi.close(); } catch (Exception exx) { } try { fi.close(); } catch (Exception exx) { } } return result; }
// post: input is closed public void close() { try { input.close(); } catch (IOException e) { throw new RuntimeException(e.toString()); } }
/** DOCUMENT ME! */ public void loadRaids() { File f = new File(REPO); if (!f.exists()) { return; } FileInputStream fIn = null; ObjectInputStream oIn = null; try { fIn = new FileInputStream(REPO); oIn = new ObjectInputStream(fIn); // de-serializing object raids = (HashMap<String, GregorianCalendar>) oIn.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { oIn.close(); fIn.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
public PtsFileConverter(GetOpt opts) { FileInputStream fin; DataInputStream ins = null; FileWriter fout = null; try { String inFileString = opts.getString("infile"); String[] inFiles = inFileString.split(","); fout = new FileWriter(opts.getString("outfile"), false); for (int i = 0; i < inFiles.length; i++) { fin = new FileInputStream(inFiles[i]); ins = new DataInputStream(fin); FeatureCategory type; if (opts.getString("type").equals("color")) { type = FeatureCategory.COLOR; } else if (opts.getString("type").equals("shape")) { type = FeatureCategory.SHAPE; } else { type = FeatureCategory.SIZE; } if (ins != null && fout != null) { convertFile(ins, fout, type); } ins.close(); fin.close(); } } catch (Exception ex) { System.err.println("ERR: " + ex); ex.printStackTrace(); } }
/** * Reload properties. This clears out the existing entries, loads the main properties file and * then adds any additional properties there may be (usually from zip files). This is used * internally by addProps() and removeProps(). */ private synchronized void reload() { // clear out old entries clear(); // read from the primary file if (file != null && file.exists()) { FileInputStream bpin = null; try { bpin = new FileInputStream(file); load(bpin); } catch (Exception x) { System.err.println("Error reading properties from file " + file + ": " + x); } finally { try { bpin.close(); } catch (Exception ignore) { // ignored } } } // read additional properties from zip files, if available if (additionalProps != null) { for (Iterator i = additionalProps.values().iterator(); i.hasNext(); ) putAll((Properties) i.next()); } lastread = System.currentTimeMillis(); }
private Parser readContent() { Parser infoParser; String filename = FILE_READ_PATH + FILE_READ_BASE_NAME + "." + FILE_READ_EXT_NUM; FILE_READ_EXT_NUM++; try { File file = new File(filename); if (DEBUG) displayMessage( "DEBUG", "WCNForecastWeatherQueryFn.readContent:: File " + filename + " file.length=" + file.length()); byte bytes[] = new byte[(int) (file.length())]; FileInputStream fis = new FileInputStream(file); int cnt = fis.read(bytes, 0, bytes.length); if (DEBUG) displayMessage( "DEBUG", "WCNForecastWeatherQueryFn.readContent:: File " + filename + " read cnt=" + cnt); fis.close(); if (cnt != bytes.length) return null; String content = new String(bytes); infoParser = new Parser(content, true, display); } catch (FileNotFoundException e) { if (DEBUG) displayMessage("ERROR", "File " + filename + " not found."); return null; } catch (IOException e) { if (DEBUG) displayMessage("ERROR", "Read failed on file " + filename); return null; } return infoParser; }
/** * Lis et retourne une piece depuis le fichier temporaire sur le disque (la piece doit exister) * * @param num : numéros de la piece */ private synchronized byte[] readPieceTmpFile(int num) { if (num < 0 || num >= this.nbPieces()) { throw new IllegalArgumentException(); } try { FileInputStream reader_tmp = new FileInputStream(this); FileChannel reader = reader_tmp.getChannel(); int index_piece = Tools.readInt(reader, 4 + _key.length() + 4 + 4 + 4 * num); if (index_piece < 0) { throw new IllegalArgumentException(); } int size = _piecesize; if (num == this.nbPieces() - 1) { size = _size - _piecesize * (this.nbPieces() - 1); } byte[] piece = Tools.readBytes(reader, this.headerSize() + _piecesize * index_piece, size); reader_tmp.close(); return piece; } catch (Exception e) { System.out.println("Unable to read tmp file piece"); e.printStackTrace(); } return new byte[0]; }
/** * @ensures: if input file is read, a String is filled with words from file and searched in * dictionary list, and if found increase words found counter, otherwise increase words not * found. Otherwise error reading file */ public void readFileOliver() { try { FileInputStream inf = new FileInputStream(new File("oliver.txt")); char let; String str = ""; String key = ""; int n = 0; while ((n = inf.read()) != -1) { let = (char) n; if (Character.isLetter(let)) { str += Character.toLowerCase(let); } if ((Character.isWhitespace(let) || let == '-') && !str.isEmpty()) { key = str; str = ""; boolean a = dictionary[(int) key.charAt(0) - 97].contains(key); if (a == true) { counter = dictionary[(int) key.charAt(0) - 97].indexOf(key); counterWFound++; counterWFCompared += counter; } else { counter = dictionary[(int) key.charAt(0) - 97].indexOf( dictionary[(int) key.charAt(0) - 97].getLast()); counterWNotFound++; counterWNFCompared += counter; } } } inf.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * reads faculty list file * * @return LinkedList<Faculty> * @throws FileNotFoundException */ public LinkedList<Faculty> readFacultyList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("facultyList.csv"); LinkedList<Faculty> facultyList = new LinkedList<Faculty>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates faculty member Faculty newFaculty = new Faculty(userName, password, email, firstName, lastName, office, phoneNumber); facultyList.add(newFaculty); } fstream.close(); } catch (Exception e) { facultyList = null; } Collections.sort(facultyList); return facultyList; }
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 boolean parse(String filename) { try { // creating a handle with 'r' rights to access the file FileInputStream fstream = new FileInputStream(filename); // creating a buffered reader to read line by line BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); List<cAddy> pp = new ArrayList<cAddy>(); // temporary string that always holds one line of the text file String s; String l[]; // read a line and s<--line try { while ((s = br.readLine()) != null) { l = s.split("\t"); if (l.length == 7) { try { pp.add( new cAddy( // <interpreting the text input> Integer.parseInt(l[2]), // PLZ l[4], // village name l[6], // kanton Integer.parseInt( l[0]), // dunno what, maybe some internal number the post uses Integer.parseInt(l[1]), // no clue what this number stands for Integer.parseInt( l[3]) // looks like an iterator of the different village names // </interpreting the text input> )); } catch (NumberFormatException e) { if (verbose) // the show must go on System.out.println("Error: converting some numbers in \'" + s + "\' failed!"); } } else { if (verbose && !s.equals("")) // printing some debug information (if wanted) System.out.println("Error: Splitting \'" + s + "\' by tabs returns an invalid result!"); } } // unregging the access handle fstream.close(); Collections.sort(pp); PLZlist = pp; return true; } catch (IOException e) { if (verbose) // fails reading it... so nothing's returned System.out.println("Error: can't access \'" + filename + "\'!"); return false; } // sorting the list for binsearch } catch (FileNotFoundException e) { // please specify a valid file if (verbose) // fails reading it... so nothing's returned System.out.println("Error: File \'" + filename + "\' not found!"); return false; } }
static void processFile(String fname, PrintStream out) throws IOException { System.err.println("Processing: " + fname); FileInputStream fio = new FileInputStream(new File(fname)); InputStreamReader fread = new InputStreamReader(fio, JetTest.encoding); BufferedReader fp = new BufferedReader(fread); StringBuffer buf = new StringBuffer(); int docno = 0, allsents = 0, processedsents = 0; while (true) { String line = fp.readLine(); // EOF or an empty line: the end of a Document. if (line == null || line.equals("")) { if (0 < buf.length()) { SGMLProcessor.allTags = true; Document doc = SGMLProcessor.sgmlToDoc(buf.toString(), (String[]) null); doc.setSGMLwrapMargin(0); System.err.println( "Doc-" + docno + ": sents=" + allsents + ", processed=" + processedsents); processDoc1(doc, docno); writeDoc1(doc, out); out.flush(); buf = new StringBuffer(); docno++; allsents = 0; processedsents = 0; } if (line == null) { break; } else { continue; } } if (line.startsWith("#")) { // "#" indicates a comment line. buf.append(line + "\n"); } else { allsents++; if (processedsents < MaxProcessSentences) { buf.append("<sentence>"); String[] words = line.split(" "); for (int i = 0; i < words.length; i++) { if (0 != words[i].length()) { buf.append("<token>" + words[i] + " </token>"); } } buf.append("</sentence>\n"); processedsents++; } } } fp.close(); fread.close(); fio.close(); return; }
private Properties loadOldProperties(File oldPropsFile) throws IOException { Properties oldProps = new Properties(); if (oldPropsFile.exists()) { FileInputStream is = new FileInputStream(oldPropsFile); oldProps.load(is); is.close(); } return oldProps; }
public static void copyFileToTheStandardOutput(String inputFileName) throws IOException { FileInputStream fis = new FileInputStream(inputFileName); int c; while ((c = fis.read()) != -1) { System.out.write(c); // won't work with big files as something // can write on the screen in the middle of the reading } fis.close(); }
/** * Load text string from a given file. * * @param fileStr the name of the file to be loaded. * @return A text string that is the content of the file. if the given file is not exist, then * return null. */ public static String getStringFromFile(String fileStr) throws Exception { String getStr = null; FileInputStream pspInputStream = new FileInputStream(fileStr); byte[] pspFileBuffer = new byte[pspInputStream.available()]; pspInputStream.read(pspFileBuffer); pspInputStream.close(); getStr = new String(pspFileBuffer); return (getStr); }
/** * reads course list file * * @return LinkedList<CurrentCourse> * @throws FileNotFoundException */ public LinkedList<CurrentCourse> readCourseList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("courseList.csv"); LinkedList<CurrentCourse> courseList = new LinkedList<CurrentCourse>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // read file while (input.hasNextLine()) { String crn; crn = input.next(); String course = input.next(); int section = input.nextInt(); String title = input.next(); String prer = input.next(); int credits = input.nextInt(); String time = input.next(); String days = input.next(); String building = input.next(); String room = input.next(); int totalSeats = input.nextInt(); int filledSeats = input.nextInt(); String tempWaiting = input.next(); String professor = input.nextLine(); professor = professor.substring(1, professor.length()); // create current course CurrentCourse newCourse = new CurrentCourse( crn, course, section, title, prer, credits, time, days, building, room, professor, totalSeats, filledSeats, tempWaiting); courseList.add(newCourse); fstream.close(); } } catch (Exception e) { courseList = null; } Collections.sort(courseList); return courseList; }
/** Metodo que le os clientes de um ficheiro */ public void lerobjLocalidades(String fileLocalidades) throws FileNotFoundException, IOException, ClassNotFoundException { FileInputStream fisloc = new FileInputStream(fileLocalidades); ObjectInputStream oisloc = new ObjectInputStream(fisloc); this.localidades = (TreeMap<String, Localidade>) oisloc.readObject(); oisloc.close(); fisloc.close(); }
public static Charset guessEncoding(File f, int bufferLength, Charset defaultCharset) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(f); byte[] buffer = new byte[bufferLength]; fis.read(buffer); fis.close(); CharsetToolkit toolkit = new CharsetToolkit(buffer); toolkit.setDefaultCharset(defaultCharset); return toolkit.guessEncoding(); }
public static void main(String[] args) { byte[] T, U, V; int[] A; int i, j, n, pidx; long start, finish; for (i = 0; i < args.length; ++i) { System.out.print(args[i] + ": "); try { /* Open a file for reading. */ File f = new File(args[i]); FileInputStream s = new FileInputStream(f); n = (int) f.length(); System.out.print(n + " bytes ... "); /* Allocate 5n bytes of memory. */ T = new byte[n]; U = new byte[n]; V = new byte[n]; A = new int[n]; /* Read n bytes of data. */ s.read(T); s.close(); s = null; f = null; /* Construct the suffix array. */ start = new Date().getTime(); pidx = new sais().bwtransform(T, U, A, n); finish = new Date().getTime(); System.out.println(((finish - start) / 1000.0) + " sec"); System.out.print("unbwtcheck ... "); unbwt(U, V, A, n, pidx); for (j = 0; j < n; ++j) { if (T[j] != V[j]) { System.err.println("error " + j + ": " + T[j] + ", " + V[j]); return; } } System.err.println("Done."); T = null; U = null; V = null; A = null; } catch (IOException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } } }
/** * reads student list file * * @return LinkedList<Student> * @throws FileNotFoundException */ public LinkedList<Student> readStudentList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("studentList.csv"); LinkedList<Student> studentList = new LinkedList<Student>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String idNumber = input.next(); String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String major = input.next(); String minor = input.next(); int approvedCredits = input.nextInt(); int creditHoursEnrolled = input.nextInt(); String currentSchudule = input.next(); String hold = input.nextLine(); hold = hold.substring(1, hold.length()); boolean holds; if (hold.equalsIgnoreCase("True")) holds = true; else holds = false; // creates student Student newStudent = new Student( idNumber, firstName, lastName, userName, password, email, major, minor, approvedCredits, creditHoursEnrolled, currentSchudule, holds); studentList.add(newStudent); fstream.close(); } } catch (Exception e) { studentList = null; } Collections.sort(studentList); return studentList; }
public static byte[] getFileBytes(File input) throws Exception { long size = input.length(); FileInputStream stream = null; try { stream = new FileInputStream(input); byte[] bytes = new StreamReader(stream).readBytes((int) size); return bytes; } finally { if (stream != null) stream.close(); } }