private Vector readlinesfromfile(String fname) { // trims lines and removes comments Vector v = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(new File(fname))); while (br.ready()) { String tmp = br.readLine(); // Strip comments while (tmp.indexOf("/*") >= 0) { int i = tmp.indexOf("/*"); v.add(tmp.substring(0, i)); String rest = tmp.substring(i + 2); while (tmp.indexOf("*/") == -1) { tmp = br.readLine(); } tmp = tmp.substring(tmp.indexOf("*/") + 2); } if (tmp.indexOf("//") >= 0) tmp = tmp.substring(0, tmp.indexOf("//")); // Strip spaces tmp = tmp.trim(); v.add(tmp); // System.out.println("Read line "+tmp); } br.close(); } catch (Exception e) { System.out.println("Exception " + e + " occured"); } return v; }
public void getWords(String fileName) throws IOException { this.word = new ArrayList<String>(); BufferedReader buf = new BufferedReader(new FileReader(fileName)); while (buf.ready()) { this.word.add(buf.readLine()); } }
/** * Locate the linux fonts based on the XML configuration file * * @param file The location of the XML file */ private static void locateLinuxFonts(File file) { if (!file.exists()) { System.err.println("Unable to open: " + file.getAbsolutePath()); return; } try { InputStream in = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); ByteArrayOutputStream temp = new ByteArrayOutputStream(); PrintStream pout = new PrintStream(temp); while (reader.ready()) { String line = reader.readLine(); if (line.indexOf("DOCTYPE") == -1) { pout.println(line); } } in = new ByteArrayInputStream(temp.toByteArray()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(in); NodeList dirs = document.getElementsByTagName("dir"); for (int i = 0; i < dirs.getLength(); i++) { Element element = (Element) dirs.item(i); String dir = element.getFirstChild().getNodeValue(); if (dir.startsWith("~")) { dir = dir.substring(1); dir = userhome + dir; } addFontDirectory(new File(dir)); } NodeList includes = document.getElementsByTagName("include"); for (int i = 0; i < includes.getLength(); i++) { Element element = (Element) dirs.item(i); String inc = element.getFirstChild().getNodeValue(); if (inc.startsWith("~")) { inc = inc.substring(1); inc = userhome + inc; } locateLinuxFonts(new File(inc)); } } catch (Exception e) { e.printStackTrace(); System.err.println("Unable to process: " + file.getAbsolutePath()); } }
FileHash(File f) { hash=new long[(int)f.length()]; length=f.length(); int i=0; int h=0; try { BufferedReader br=new BufferedReader(new FileReader(f)); while (br.ready()) { int c=br.read(); h=h+c; hash[i]=h; } br.close(); } catch (Exception e) { System.out.println("What should I do with exception "+e+" ?"); } System.out.println(""+h); }
private void parseLilyPond() { lilyHeader = new LilyHeader(name); try { BufferedReader LYIn = new BufferedReader(new FileReader("data/ly/" + name + ".ly")); int line = 1; while (LYIn.ready()) { String S = LYIn.readLine(); // TODO: detect new staff location better if ((S.contains("\\new Staff") && (S.contains("down") || S.contains("lower")) || S.contains("NEW STAFF"))) { staffLine = line; staves = 2; } for (int i = 0; i < S.length(); ++i) { if (S.charAt(i) == '~') { ArrayList<Integer> t = new ArrayList<Integer>(); t.add(line); t.add(i); ties.add(t); } } ++line; } LYIn.close(); } catch (Exception e) { System.err.println("Parsing the score from Lilypond's output has failed. Error: "); e.printStackTrace(); } notes = (Vector<NotePanel>[]) new Vector[staves]; chords = (Vector<Chord>[]) new Vector[staves]; currNotes = (Iterator<NotePanel>[]) new Iterator[staves]; for (int i = 0; i < staves; ++i) { notes[i] = new Vector<NotePanel>(); chords[i] = new Vector<Chord>(); currNotes[i] = notes[i].iterator(); } }
private String physReadTextFile(File file) { // physically read text file try { BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file))); StringBuffer tmp = new StringBuffer(); while (input.ready()) { tmp.append(input.readLine()); tmp.append("\n"); } return tmp.toString(); } catch (FileNotFoundException e) { // not sure how this can happen showErrorDialog("Unable to load \"" + file.getName() + "\" (file not found)"); } catch (IOException e) { // This happens if e.g. file already exists and // we do not have write permissions showErrorDialog("Unable to load \"" + file.getName() + "\" (I/O error)"); } return new String(""); }
static ToolBox fromStream(InputStream in, Board board) { ToolBox tb = new ToolBox(); InputStreamReader read = new InputStreamReader(in); BufferedReader buff = new BufferedReader(read); try { while (buff.ready()) { String s = buff.readLine(); SprayTool st = SprayTool.fromString(s, board); if (st != null) { tb.tools.add(st); tb.toolKeys.put(st.getHotKey(), st); } } buff.close(); tb.currentTool = tb.tools.size() > 0 ? tb.tools.get(0) : null; } catch (IOException e) { e.printStackTrace(); } return tb; }
// The main procedure public static void main(String args[]) { String s; initGUI(); while (true) { try { // Poll every ~10 ms Thread.sleep(10); } catch (InterruptedException e) { } switch (connectionStatus) { case BEGIN_CONNECT: try { // Try to set up a server if host if (isHost) { hostServer = new ServerSocket(port); socket = hostServer.accept(); } // If guest, try to connect to the server else { socket = new Socket(hostIP, port); } in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); changeStatusTS(CONNECTED, true); } // If error, clean up and output an error message catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; case CONNECTED: try { // Send data if (toSend.length() != 0) { out.print(toSend); out.flush(); toSend.setLength(0); changeStatusTS(NULL, true); } // Receive data if (in.ready()) { s = in.readLine(); if ((s != null) && (s.length() != 0)) { // Check if it is the end of a trasmission if (s.equals(END_CHAT_SESSION)) { changeStatusTS(DISCONNECTING, true); } // Otherwise, receive what text else { appendToChatBox("INCOMING: " + s + "\n"); changeStatusTS(NULL, true); } } } } catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; case DISCONNECTING: // Tell other chatter to disconnect as well out.print(END_CHAT_SESSION); out.flush(); // Clean up (close all streams/sockets) cleanUp(); changeStatusTS(DISCONNECTED, true); break; default: break; // do nothing } } }
public void jFileChooserActionPerformed(java.awt.event.ActionEvent evt) throws FileNotFoundException, IOException { File initialBoard = this.jFileChooser.getSelectedFile(); InputStream inputStream = new FileInputStream(initialBoard); Scanner scanner = new Scanner(inputStream); if (!initialBoard .getName() .toLowerCase() .contains("initialboard")) { // .toLowerCase().compareTo("initialboard")!=0){ JOptionPane.showMessageDialog( frame, "Wrong File \n Please select InitialBoard.txt", "Eror", JOptionPane.ERROR_MESSAGE); } else { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { in = new BufferedReader(new FileReader(initialBoard.getAbsolutePath())); } catch (FileNotFoundException e) { System.out.println(e.getCause()); System.out.println("Error loading initial board"); } int[] boardRows = new int[15]; // ---------------- String text = in.readLine(); StringTokenizer tokenizer = new StringTokenizer(text, " "); int boardSize = 0; while (tokenizer.hasMoreElements()) { boardRows[boardSize] = Integer.parseInt(tokenizer.nextToken()); boardSize++; } int[] newBoard = new int[boardSize * boardSize + 1]; System.arraycopy(boardRows, 0, newBoard, 1, boardSize); int index = 0; while (in.ready()) { index++; text = in.readLine(); tokenizer = new StringTokenizer(text, " "); int pos = 0; while (tokenizer.hasMoreElements()) { pos++; newBoard[index * boardSize + pos] = Integer.parseInt(tokenizer.nextToken()); } } this.jFrameFileChooser.setVisible(false); // this.boardPanel.s gameInitialBoard = new Board(newBoard, boardSize); gameBoard = new Board(newBoard, boardSize); init(); } }
private void parsePostScript() { try { BufferedReader PSIn = new BufferedReader(new FileReader("data/out/" + name + ".ps")); // parse header while (PSIn.ready()) { String S = PSIn.readLine().trim(); if (S.contains("EndSetup")) { break; } else { if (S.startsWith("/magfont")) { fontInfo.add(S); } else if (S.startsWith("/lily-output-units")) { outputUnits = Float.parseFloat(S.split(" ")[1]); for (String T : fontInfo) { addFont( T.split(" ")[0].substring(1), T.split(" ")[2].substring(1), (float) outputUnits * Float.parseFloat(T.split(" ")[3])); } } else if (S.startsWith("/output-scale")) { outputScale = Float.parseFloat(S.split(" ")[1]); } else if (S.startsWith("/staff-height")) { staffLineHeight = Float.parseFloat(S.split(" ")[1]) / 4; } } } scale = outputUnits * outputScale; for (int layer = 0; layer < staves; ++layer) { Vector<Vector<Double>> staff = new Vector<Vector<Double>>(); for (int page = 0; page < pages; ++page) { staff.add(new Vector<Double>()); } staffLines.add(staff); } Vector<Double> cStaffs = new Vector<Double>(); String prevLine = ""; int currPage = 1; // parse the rest of the file while (PSIn.ready()) { String S = PSIn.readLine().trim(); if (S.contains("noteheads") || S.contains("rests")) { // extract coordinate, glyph, and font information String T[] = S.split(" "); NotePanel N = new NotePanel(); N.setCoordinates(Double.parseDouble(T[0]), -Double.parseDouble(T[1])) .setGlyph(T[4].substring(1)) .setGonville(fonts.get(T[3])); if (S.contains("rests")) { T = S.substring(S.lastIndexOf("rests")).split("[. ]"); N.setRest(Integer.parseInt(T[1])); } T = prevLine.substring(prevLine.lastIndexOf(this.name + ".ly")).split(":"); N.setLine(Integer.parseInt(T[1]), Integer.parseInt(T[2])).setPage(currPage); if (N.lyLine < staffLine || staffLine == 0) { notes[0].add(N); } else { notes[1].add(N); } } else if (S.contains("accidentals")) { // String T[] = S.split(" "); // lastNote.setAccidentals(Double.parseDouble(T[0]), -Double.parseDouble(T[1]), // T[4].substring(1), T[3]); } else if (S.startsWith("%%Page:")) { currPage = Integer.parseInt(S.split(" ")[1]); } if (S.contains("draw_line")) { cStaffs.add(-Double.parseDouble(S.split(" ")[1])); if (cStaffs.size() >= 5 * staves) { // found a full staff Collections.sort(cStaffs); staffLines.get(0).get(currPage - 1).add(cStaffs.get(4) + staffLineHeight); if (staves > 1) { staffLines.get(1).get(currPage - 1).add(cStaffs.get(5) - staffLineHeight); } cStaffs.clear(); } } else if (!S.contains("draw_round_box")) { cStaffs.clear(); } if (S.contains(this.name + ".ly")) { prevLine = S; } } // sort the notes we found from the PS by where they occurred in the .ly for (int i = 0; i < staves; ++i) { Collections.sort(notes[i]); } // find tied notes for (int i = 0; i < staves; ++i) { int cTie = 0; int cNote = 0; while (cTie < ties.size() && cNote < notes[i].size() - 1) { ArrayList<Integer> tie = ties.get(cTie); NotePanel prevNote = notes[i].get(cNote); NotePanel nextNote = notes[i].get(cNote + 1); if (pairComp(tie.get(0), tie.get(1), prevNote.lyLine, prevNote.lyNumber) != -1 && pairComp(tie.get(0), tie.get(1), nextNote.lyLine, nextNote.lyNumber) != 1) { // tie is located between these notes nextNote.setTie(true); ++cNote; ++cTie; } else if (pairComp(tie.get(0), tie.get(1), prevNote.lyLine, prevNote.lyNumber) != -1) { ++cNote; } else { ++cTie; } } } PSIn.close(); } catch (Exception e) { System.err.println("Parsing the score from Lilypond's output has failed. Error: "); e.printStackTrace(); } }
/** * Read position and size of the login box from a given abstract path. * * @param abstractPath The path to the file. */ public void readPersistence(String abstractPath) { String filepath = FileUtil.openPath(abstractPath); if (filepath != null) { BufferedReader in; String line; try { File file = new File(filepath); in = new BufferedReader(new FileReader(file)); // File must start with 'Login Panel' if ((line = in.readLine()) != null) { if (!line.startsWith("Login Panel")) { Messages.postWarning("The " + filepath + " file is " + "corrupted and being removed"); // Remove the corrupted file. file.delete(); // Set the size and position to the full vnmrj frame setDefaultSizePosition(); return; } } String h = null, w = null, x = null, y = null; int xi, yi; if (in.ready()) h = in.readLine().trim(); if (in.ready()) w = in.readLine().trim(); if (in.ready()) x = in.readLine().trim(); if (in.ready()) y = in.readLine().trim(); in.close(); // Save width and height for later use also height = Integer.decode(h).intValue(); width = Integer.decode(w).intValue(); xi = Integer.decode(x).intValue(); yi = Integer.decode(y).intValue(); // Save point for later use also position = new Point(xi, yi); // Set them setSize(width, height); setLocation(position); // If we got what we need and set the size and position, // just return now. return; } // If an exception, continue below catch (Exception e) { } } // No file or an excpetion happened, set default size and position // Be sure the file is gone try { if (filepath != null) { File file = new File(filepath); if (file != null) file.delete(); } } // If an exception, just continue below catch (Exception e) { } // Set the size and position to the full vnmrj frame setDefaultSizePosition(); }