コード例 #1
1
  private void sendResourceFile(HttpExchange exchange) {
    StringBuilder response = new StringBuilder();

    String path = exchange.getRequestURI().getPath();
    if (path.contains("resources")) {
      path = path.substring(path.indexOf("resources") + 9);
    }
    InputStream is = MyBaseHandler.class.getResourceAsStream(path);
    if (is == null) {
      writeResponse(exchange, "File not found", 404);
      return;
    }
    InputStreamReader reader = new InputStreamReader(is);

    try {
      BufferedReader bufferedReader = new BufferedReader(reader);

      String tmp;
      while ((tmp = bufferedReader.readLine()) != null) {
        response.append(tmp);
        response.append("\n");
      }
    } catch (NullPointerException e) {
      response.append("Resource file not found");
      writeResponse(exchange, response.toString(), 404);
    } catch (IOException e) {
      response.append("Error while reading from file");
      writeResponse(exchange, response.toString(), 400);
    }
    writeResponse(exchange, response.toString(), 200);
  }
コード例 #2
0
ファイル: Main.java プロジェクト: joeytwiddle/code
 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;
 }
コード例 #3
0
ファイル: TileMap.java プロジェクト: Joneser/Platformer
  public void loadMap(String s) {

    try {
      InputStream in = getClass().getResourceAsStream(s);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      numCols = Integer.parseInt(br.readLine());
      numRows = Integer.parseInt(br.readLine());
      map = new int[numRows][numCols];
      width = numCols * tileSize;
      height = numRows * tileSize;

      xmin = GamePanel.WIDTH - width;
      xmax = 0;
      ymin = GamePanel.HEIGHT - height;
      ymax = 0;

      String delims = "\\s+";
      for (int row = 0; row < numRows; row++) {
        String line = br.readLine();
        String[] tokens = line.split(delims);
        for (int col = 0; col < numCols; col++) {
          map[row][col] = Integer.parseInt(tokens[col]);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #4
0
ファイル: TileMap.java プロジェクト: john0xff/JavaGames-src
  public TileMap(String s, int tileSize) {

    this.tileSize = tileSize;

    try {

      BufferedReader br = new BufferedReader(new FileReader(s));

      mapWidth = Integer.parseInt(br.readLine());
      mapHeight = Integer.parseInt(br.readLine());
      map = new int[mapHeight][mapWidth];

      minx = GamePanel.WIDTH - mapWidth * tileSize;
      miny = GamePanel.HEIGHT - mapHeight * tileSize;

      String delimiters = "\\s+";
      for (int row = 0; row < mapHeight; row++) {
        String line = br.readLine();
        String[] tokens = line.split(delimiters);
        for (int col = 0; col < mapWidth; col++) {
          map[row][col] = Integer.parseInt(tokens[col]);
        }
      }

    } catch (Exception e) {
    }
  }
コード例 #5
0
ファイル: Chart.java プロジェクト: feihugis/NetCDF
  public Chart(String filename) {
    try {
      // Get Stock Symbol
      this.stockSymbol = filename.substring(0, filename.indexOf('.'));

      // Create time series
      TimeSeries open = new TimeSeries("Open Price", Day.class);
      TimeSeries close = new TimeSeries("Close Price", Day.class);
      TimeSeries high = new TimeSeries("High", Day.class);
      TimeSeries low = new TimeSeries("Low", Day.class);
      TimeSeries volume = new TimeSeries("Volume", Day.class);

      BufferedReader br = new BufferedReader(new FileReader(filename));
      String key = br.readLine();
      String line = br.readLine();
      while (line != null && !line.startsWith("<!--")) {
        StringTokenizer st = new StringTokenizer(line, ",", false);
        Day day = getDay(st.nextToken());
        double openValue = Double.parseDouble(st.nextToken());
        double highValue = Double.parseDouble(st.nextToken());
        double lowValue = Double.parseDouble(st.nextToken());
        double closeValue = Double.parseDouble(st.nextToken());
        long volumeValue = Long.parseLong(st.nextToken());

        // Add this value to our series'
        open.add(day, openValue);
        close.add(day, closeValue);
        high.add(day, highValue);
        low.add(day, lowValue);

        // Read the next day
        line = br.readLine();
      }

      // Build the datasets
      dataset.addSeries(open);
      dataset.addSeries(close);
      dataset.addSeries(low);
      dataset.addSeries(high);
      datasetOpenClose.addSeries(open);
      datasetOpenClose.addSeries(close);
      datasetHighLow.addSeries(high);
      datasetHighLow.addSeries(low);

      JFreeChart summaryChart = buildChart(dataset, "Summary", true);
      JFreeChart openCloseChart = buildChart(datasetOpenClose, "Open/Close Data", false);
      JFreeChart highLowChart = buildChart(datasetHighLow, "High/Low Data", true);
      JFreeChart highLowDifChart =
          buildDifferenceChart(datasetHighLow, "High/Low Difference Chart");

      // Create this panel
      this.setLayout(new GridLayout(2, 2));
      this.add(new ChartPanel(summaryChart));
      this.add(new ChartPanel(openCloseChart));
      this.add(new ChartPanel(highLowChart));
      this.add(new ChartPanel(highLowDifChart));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #6
0
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
コード例 #7
0
ファイル: ScoreParser.java プロジェクト: emtwo/piano
  private static void exec(String command) {
    try {
      System.out.println("Invoking: " + command);
      Process p = Runtime.getRuntime().exec(command);

      // get standard output
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line;
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      // get error output
      input = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      p.waitFor();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
コード例 #8
0
ファイル: LibCommon.java プロジェクト: numerodix/gridportal
  public String readFileFromJAR(String filepath) {

    String out = "";

    try {

      // setup input buffer
      ClassLoader cl = this.getClass().getClassLoader();
      InputStream instream = cl.getResourceAsStream(filepath);
      BufferedReader filereader = new BufferedReader(new InputStreamReader(instream));

      // read lines
      String line = filereader.readLine();
      while (line != null) {
        out += "\n" + line;
        line = filereader.readLine();
      }

      filereader.close();

    } catch (Exception e) {
      // e.printStackTrace();
    }

    return out;
  }
コード例 #9
0
ファイル: MainActivity.java プロジェクト: etochy/test
  public void lire() {
    int x = 0;
    try {
      File f = new File(_cheminInit);
      FileReader fr = new FileReader(f);
      BufferedReader br = new BufferedReader(fr);
      try {
        // initialisation
        String line = br.readLine();
        _poids = Double.parseDouble(line) * 9.81;
        line = br.readLine();
        _pasTemps = Double.parseDouble(line);

        line = br.readLine();
        while (line != null) {
          _tabDonnee.add(Double.parseDouble(line));
          ++x;
          line = br.readLine();
        }
        br.close();
        fr.close();
      } catch (IOException exception) {
        System.out.println("Erreur : " + exception.getMessage());
      }
    } catch (FileNotFoundException exception) {
      System.out.println("Erreur : Fichier non trouvé");
    }
  }
コード例 #10
0
ファイル: Main.java プロジェクト: MathBunny/ccc-solutions
  public Main() {
    try {
      BufferedReader in;
      in = new BufferedReader(new InputStreamReader(System.in)); // Used for CCC
      int numLights = Integer.parseInt(in.readLine());
      int[] states = new int[numLights];
      for (int i = 0; i < numLights; i++) {
        states[i] = Integer.parseInt(in.readLine());
      }
      ArrayDeque<Scenario> Q = new ArrayDeque<Scenario>();
      HashMap<String, Integer> dp = new HashMap<String, Integer>();

      int moves = 0;
      Q.addLast(new Scenario(states));
      while (!Q.isEmpty()) {
        int size = Q.size();
        for (int q = 0; q < size; q++) {
          Scenario temp = Q.removeFirst();
          if (isEmpty(temp.states)) {
            System.out.println(moves);
            return;
          } else {
            for (int i = 0; i < temp.states.length; i++) {
              if (temp.states[i] == 0) {
                int[] newArr = Arrays.copyOf(temp.states, temp.states.length);
                newArr[i] = 1;
                newArr = fixArray(newArr);
                String arr = "";
                for (int p = 0; p < newArr.length; p++) arr += newArr[p];
                if (dp.get(arr) == null) {
                  dp.put(arr, moves);
                  Q.addLast(new Scenario(newArr));
                } else {
                  int val = dp.get(arr);
                  if (val != 0 && moves < val) {
                    dp.put(arr, moves);
                    Q.addLast(new Scenario(newArr));
                  }
                }

                // outputArr(newArr);
              }
            }
          }
        }
        moves++;
      }

    } catch (IOException e) {
      System.out.println("IO: General");
    }
  }
コード例 #11
0
  public void open(File file) {
    try {
      BufferedReader in = new BufferedReader(new FileReader(file));
      game = "";

      for (String s = in.readLine(); s != null; s = in.readLine()) {
        game += s + "\n";
      }
      game.trim();
      in.close();
    } catch (IOException e) {
      System.out.println("File I/O error!");
    }
  }
コード例 #12
0
ファイル: WinSize.java プロジェクト: McNeight/GLsat
  void doSourceFileUpdate() {
    BufferedReader bufferIn = null;
    String str1 = new String();
    String strContent = new String();
    String sliderValue = new String();
    String newLine = System.getProperty("line.separator");
    StringBuffer strBuf = new StringBuffer();
    int posFound = 0;
    int i = 0;
    PSlider slider;

    // Read the original source file to input buffer
    try {
      bufferIn = new BufferedReader(new FileReader(exampleSource));
    } catch (FileNotFoundException fe) {
      System.err.println("Example Source File not found " + fe);
      System.exit(-1);
    }
    // get the first line of the buffer.
    try {
      str1 = bufferIn.readLine();
    } catch (IOException ie) {
      System.err.println("Error reading line from the buffer " + ie);
      System.exit(-1);
    }
    // Transfer the whole content of the input buffer to the string
    try {
      do strContent += str1 + newLine;
      while ((str1 = bufferIn.readLine()) != null);
    } catch (IOException ie) {
      System.err.println("Error readding content of the input buffer " + ie);
      System.exit(-1);
    }
    // do the replacement.

    for (i = 0; i < COMPONENTS; i++) {
      // get the current value of slider
      slider = (PSlider) vSlider.elementAt(i);
      sliderValue = slider.getValue();
      // construct the search string
      str1 = "$$$" + (i + 1);
      // get the position of the search string in the content string.
      strBuf = new StringBuffer(strContent);
      posFound = strContent.indexOf(str1);
      strBuf.replace(posFound, posFound + str1.length(), sliderValue);
      strContent = new String(strBuf);
    }
    textPane.setText(strContent);
  }
コード例 #13
0
ファイル: Client.java プロジェクト: Eneru/l3s6
  public void init() {
    add(intitule);
    add(texte);
    add(bouton);
    bouton.addActionListener(this);

    try {
      ORB orb = ORB.init(this, null);
      FileReader file = new FileReader(iorfile.value);
      BufferedReader in = new BufferedReader(file);
      String ior = in.readLine();
      file.close();
      org.omg.CORBA.Object obj = orb.string_to_object(ior);
      annuaire = AnnuaireHelper.narrow(obj);

    } catch (org.omg.CORBA.SystemException ex) {
      System.err.println("Error");
      ex.printStackTrace();
    } catch (FileNotFoundException fnfe) {
      System.err.println(fnfe.getMessage());
    } catch (IOException io) {
      System.err.println(io.getMessage());
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
  }
コード例 #14
0
    protected void writeAuditTrail(String strPath, String strUser, StringBuffer sbValues) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;
      ArrayList aListData = WUtil.strToAList(sbValues.toString(), false, "\n");
      StringBuffer sbData = sbValues;
      String strPnl = (this instanceof DisplayTemplate) ? "Data Template " : "Data Dir ";
      if (reader == null) {
        Messages.postDebug("Error opening file " + strPath);
        return;
      }

      try {
        while ((strLine = reader.readLine()) != null) {
          // if the line in the file is not in the arraylist,
          // then that line has been deleted
          if (!aListData.contains(strLine))
            WUserUtil.writeAuditTrail(new Date(), strUser, "Deleted " + strPnl + strLine);

          // remove the lines that are also in the file or those which
          // have been deleted.
          aListData.remove(strLine);
        }

        // Traverse through the remaining new lines in the arraylist,
        // and write it to the audit trail
        for (int i = 0; i < aListData.size(); i++) {
          strLine = (String) aListData.get(i);
          WUserUtil.writeAuditTrail(new Date(), strUser, "Added " + strPnl + strLine);
        }
        reader.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
コード例 #15
0
ファイル: ClientGui.java プロジェクト: timburrow/ovj3
  public CryoBay reconnectServer(ORB o, ReconnectThread rct) {

    BufferedReader reader;
    File file;
    ORB orb;
    org.omg.CORBA.Object obj;

    orb = o;

    obj = null;
    cryoB = null;

    try {
      // instantiate ModuleAccessor
      file = new File("/vnmr/acqqueue/cryoBay.CORBAref");
      if (file.exists()) {
        reader = new BufferedReader(new FileReader(file));
        obj = orb.string_to_object(reader.readLine());
      }

      if (obj != null) {
        cryoB = CryoBayHelper.narrow(obj);
      }

      if (cryoB != null) {
        if (!(cryoB._non_existent())) {
          // System.out.println("reconnected!!!!");
          rct.reconnected = true;
        }
      }
    } catch (Exception e) {
      // System.out.println("Got error: " + e);
    }
    return cryoB;
  }
コード例 #16
0
ファイル: Talker.java プロジェクト: JohnnyBall/FOSh
 // =========================================================
 public String recieve() throws IOException // RECIEVE METHOD
     {
   String recievedString;
   recievedString = buffRdr.readLine();
   System.out.println("RECD<<<< " + id + ": " + recievedString);
   return recievedString;
 }
コード例 #17
0
ファイル: SampleApp.java プロジェクト: kdanninger/jac444a-3
  public void getSavedLocations() {
    // System.out.println("inside getSavedLocations");				//CONSOLE * * * * * * * * * * * * *
    loc.clear(); // clear locations.  helps refresh the list when reprinting all the locations
    BufferedWriter f = null; // just in case file has not been created yet
    BufferedReader br = null;
    try {
      // attempt to open the locations file if it doesn't exist, create it
      f =
          new BufferedWriter(
              new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist
      br = new BufferedReader(new FileReader("savedLocations.txt"));

      String line; // each line is one index of the list
      loc.add("Saved Locations");
      // loop and read a line from the file as long as we don't get null
      while ((line = br.readLine()) != null)
        // add the read word to the wordList
        loc.add(line);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        // attempt the close the file

        br.close(); // close bufferedwriter
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
コード例 #18
0
 /** This method receives the URL as input and returns the same as array of string. */
 public static String[] readStringArrayFromURL(URL u) {
   Vector vs = new Vector();
   String sdat[] = (String[]) null;
   if (u != null) {
     try {
       java.io.InputStream in = u.openStream();
       BufferedReader bis = new BufferedReader(new InputStreamReader(in));
       do {
         String line = bis.readLine();
         if (line == null) {
           break;
         }
         vs.addElement(line);
       } while (true);
     } catch (IOException ex) {
       System.out.println("URL read error ");
     }
     if (vs.size() > 0) {
       sdat = new String[vs.size()];
       for (int i = 0; i < vs.size(); i++) {
         sdat[i] = (String) (String) vs.elementAt(i);
       }
     }
   }
   return sdat;
 }
コード例 #19
0
ファイル: MiscUtilities.java プロジェクト: zukov/Jpicedt
  /**
   * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from
   *     jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty.
   */
  public static String getClipboardStringContent(Clipboard clipboard) {
    // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
      String selection =
          (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor));
      if (selection == null) return null;

      boolean trailingEOL =
          (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator")));

      // Some Java versions return the clipboard contents using the native line separator,
      // so have to convert it here , see jEdit's "registers.java"
      BufferedReader in = new BufferedReader(new StringReader(selection));
      StringBuffer buf = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        buf.append(line);
        buf.append('\n');
      }
      // remove trailing \n
      if (!trailingEOL) buf.setLength(buf.length() - 1);
      return buf.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
コード例 #20
0
ファイル: WPart11Dialog.java プロジェクト: timburrow/ovj3
    protected void buildPanel(String strPath) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;

      if (reader == null) return;

      try {
        while ((strLine = reader.readLine()) != null) {
          if (strLine.startsWith("#") || strLine.startsWith("%") || strLine.startsWith("@"))
            continue;

          StringTokenizer sTokLine = new StringTokenizer(strLine, ":");

          // first token is the label e.g. Password Length
          if (sTokLine.hasMoreTokens()) {
            createLabel(sTokLine.nextToken(), this);
          }

          // second token is the value
          String strValue = sTokLine.hasMoreTokens() ? sTokLine.nextToken() : "";
          if (strValue.equalsIgnoreCase("yes") || strValue.equalsIgnoreCase("no"))
            createChkBox(strValue, this);
          else createTxf(strValue, this);
        }
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
コード例 #21
0
ファイル: LoginBox.java プロジェクト: timburrow/ovj3
  protected String gettitle(String strFreq) {
    StringBuffer sbufTitle = new StringBuffer().append("VnmrJ  ");
    String strPath = FileUtil.openPath(FileUtil.SYS_VNMR + "/vnmrrev");
    BufferedReader reader = WFileUtil.openReadFile(strPath);
    String strLine;
    String strtype = "";
    if (reader == null) return sbufTitle.toString();

    try {
      while ((strLine = reader.readLine()) != null) {
        strtype = strLine;
      }
      strtype = strtype.trim();
      if (strtype.equals("merc")) strtype = "Mercury";
      else if (strtype.equals("mercvx")) strtype = "Mercury-Vx";
      else if (strtype.equals("mercplus")) strtype = "MERCURY plus";
      else if (strtype.equals("inova")) strtype = "INOVA";
      String strHostName = m_strHostname;
      if (strHostName == null) strHostName = "";
      sbufTitle.append("    ").append(strHostName);
      sbufTitle.append("    ").append(strtype);
      sbufTitle.append(" - ").append(strFreq);
      reader.close();
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.logError(e.toString());
    }

    return sbufTitle.toString();
  }
コード例 #22
0
ファイル: LicenseDialog.java プロジェクト: CoCoViLa/CoCoViLa
  /**
   * Get the Lincese text from a text file specified in the PropertyBox.
   *
   * @return String - License text.
   */
  public String getLicenseText() {
    StringBuffer textBuffer = new StringBuffer();
    try {
      String fileName = RuntimeProperties.GPL_EN_LICENSE_FILE_NAME;
      if (cbLang != null
          && cbLang.getSelectedItem() != null
          && cbLang.getSelectedItem().toString().equalsIgnoreCase("Eesti")) {
        fileName = RuntimeProperties.GPL_EE_LICENSE_FILE_NAME;
      }

      InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName);

      if (is == null) return "";

      BufferedReader in = new BufferedReader(new InputStreamReader(is));
      String str;
      while ((str = in.readLine()) != null) {
        textBuffer.append(str);
        textBuffer.append("\n");
      }
      in.close();
    } catch (IOException e) {
      logger.error(null, e);
    }
    return textBuffer.toString();
  } // getLicenseText
コード例 #23
0
ファイル: Server.java プロジェクト: psy-core/probackup
 public void run() {
   try {
     theInputStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
     theOutputStream = new PrintStream(client.getOutputStream());
     while (true) {
       readin = theInputStream.readLine();
       chat.ta.append(readin + "\n");
     }
   } catch (SocketException e) {
     chat.ta.append("连接中断!\n");
     chat.clientBtn.setEnabled(true);
     chat.serverBtn.setEnabled(true);
     chat.tfaddress.setEnabled(true);
     chat.tfport.setEnabled(true);
     try {
       i--;
       skt.close();
       client.close();
     } catch (IOException err) {
       chat.ta.append(err.toString());
     }
   } catch (IOException e) {
     chat.ta.append(e.toString());
   }
 }
コード例 #24
0
ファイル: EPSImporter.java プロジェクト: octo-byte/BeamForge
 /**
  * Tries to read the BoundingBox out of the EPS file. If not successful, it returns a default
  * BoundingBox
  *
  * @param epsfile
  * @return
  */
 private Rectangle2D getBoundingBox(File epsfile) {
   Rectangle.Double result = new Rectangle.Double(0, 0, 800, 600);
   try {
     BufferedReader r = new BufferedReader(new FileReader(epsfile));
     String line;
     while ((line = r.readLine()) != null) {
       // TODO: Get HighRes BoundingBox
       if (line.startsWith("%%BoundingBox:") || line.startsWith("%%PageBoundingBox:")) {
         try {
           String[] elements = line.split(" ");
           result =
               new Rectangle.Double(
                   Integer.parseInt(elements[1]),
                   Integer.parseInt(elements[2]),
                   Integer.parseInt(elements[3]),
                   Integer.parseInt(elements[4]));
           break;
         } catch (NumberFormatException e) {
         }
       }
     }
     r.close();
   } catch (Exception ex) {
     Logger.getLogger(EPSImporter.class.getName()).log(Level.SEVERE, null, ex);
   }
   return result;
 }
コード例 #25
0
ファイル: WordSearch.java プロジェクト: InsidiousMind/CMPS144
 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());
   }
 }
コード例 #26
0
  // ------------------------------------
  // Parse RTSP Request
  // ------------------------------------
  private int parse_RTSP_request() {
    int request_type = -1;
    try {
      // parse request line and extract the request_type:
      String RequestLine = RTSPBufferedReader.readLine();
      // System.out.println("RTSP Server - Received from Client:");
      System.out.println(RequestLine);

      StringTokenizer tokens = new StringTokenizer(RequestLine);
      String request_type_string = tokens.nextToken();

      // convert to request_type structure:
      if ((new String(request_type_string)).compareTo("SETUP") == 0) request_type = SETUP;
      else if ((new String(request_type_string)).compareTo("PLAY") == 0) request_type = PLAY;
      else if ((new String(request_type_string)).compareTo("PAUSE") == 0) request_type = PAUSE;
      else if ((new String(request_type_string)).compareTo("TEARDOWN") == 0)
        request_type = TEARDOWN;

      if (request_type == SETUP) {
        // extract VideoFileName from RequestLine
        VideoFileName = tokens.nextToken();
      }

      // parse the SeqNumLine and extract CSeq field
      String SeqNumLine = RTSPBufferedReader.readLine();
      System.out.println(SeqNumLine);
      tokens = new StringTokenizer(SeqNumLine);
      tokens.nextToken();
      RTSPSeqNb = Integer.parseInt(tokens.nextToken());

      // get LastLine
      String LastLine = RTSPBufferedReader.readLine();
      System.out.println(LastLine);

      if (request_type == SETUP) {
        // extract RTP_dest_port from LastLine
        tokens = new StringTokenizer(LastLine);
        for (int i = 0; i < 3; i++) tokens.nextToken(); // skip unused stuff
        RTP_dest_port = Integer.parseInt(tokens.nextToken());
      }
      // else LastLine will be the SessionId line ... do not check for now.
    } catch (Exception ex) {
      System.out.println("Exception caught: " + ex);
      System.exit(0);
    }
    return (request_type);
  }
コード例 #27
0
ファイル: Spaceship.java プロジェクト: LukeJHarvey/SpaceShip
 public void readFile() {
   try {
     String inputfile = "info.txt";
     BufferedReader in = new BufferedReader(new FileReader(inputfile));
     String line = in.readLine();
     while (line != null) {
       String newLine = line.toLowerCase();
       if (newLine.startsWith("starnum")) {
         String numStarsString = newLine.substring(7);
         starNum = Integer.parseInt(numStarsString.trim());
       }
       line = in.readLine();
     }
     in.close();
   } catch (IOException ioe) {
   }
 }
コード例 #28
0
ファイル: Resource.java プロジェクト: bozhink/Code-Chunks
 /**
  * Gets a String.
  *
  * @return the string
  */
 public String getString() {
   if (string == null) {
     StringBuffer buffer = new StringBuffer();
     try {
       BufferedReader in = new BufferedReader(openReader());
       String line = in.readLine();
       while (line != null) {
         buffer.append(line + XML.NEW_LINE);
         line = in.readLine();
       }
       in.close();
     } catch (IOException ex) {
       ex.printStackTrace();
     }
     string = buffer.toString();
   }
   return string;
 }
コード例 #29
0
ファイル: GalaxyViewer.java プロジェクト: runholen/stars
 private void parseMapFile(File map) throws Exception {
   BufferedReader in = new BufferedReader(new FileReader(map));
   in.readLine();
   while (true) {
     String s = in.readLine();
     if (s == null) break;
     if (s.trim().equals("")) continue;
     String[] el = s.split("\t");
     int id = Integer.parseInt(el[0]) - 1;
     planetNames.put(id, el[3]);
     int x = Integer.parseInt(el[1]);
     int y = Integer.parseInt(el[2]);
     if (x > maxX) maxX = x;
     if (y > maxY) maxY = y;
     planetCoordinates.put(id, new Point(x, y));
   }
   in.close();
 }
コード例 #30
0
ファイル: GalaxyViewer.java プロジェクト: runholen/stars
    public static Settings init() throws Exception {
      File f = new File("galaxyviewer.ini");
      if (f.getAbsoluteFile().getParentFile().getName().equals("bin"))
        f = new File("..", "galaxyviewer.ini");
      Settings settings;
      if (f.exists()) {
        settings = new Settings();
        BufferedReader in = new BufferedReader(new FileReader(f));
        while (true) {
          String s = in.readLine();
          if (s == null) break;
          if (s.contains("=") == false) continue;
          String[] el = s.split("=", -1);
          if (el[0].equalsIgnoreCase("PlayerNr"))
            settings.playerNr = Integer.parseInt(el[1].trim()) - 1;
          if (el[0].equalsIgnoreCase("GameName")) settings.gameName = el[1].trim();
          if (el[0].equalsIgnoreCase("GameDir")) settings.directory = el[1].trim();
        }
        in.close();
      } else settings = new Settings();

      JTextField pNr = new JTextField("" + (settings.playerNr + 1));
      JTextField gName = new JTextField(settings.gameName);
      JTextField dir = new JTextField("" + settings.directory);

      JPanel p = new JPanel();
      p.setLayout(new GridLayout(3, 2));
      p.add(new JLabel("Player nr"));
      p.add(pNr);
      p.add(new JLabel("Game name"));
      p.add(gName);
      p.add(new JLabel("Game directory"));
      p.add(dir);
      gName.setToolTipText("Do not include file extensions");
      String[] el = {"Ok", "Cancel"};
      int ok =
          JOptionPane.showOptionDialog(
              null,
              p,
              "Choose settings",
              JOptionPane.OK_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              el,
              el[0]);
      if (ok != 0) System.exit(0);
      settings.playerNr = Integer.parseInt(pNr.getText().trim()) - 1;
      settings.directory = dir.getText().trim();
      settings.gameName = gName.getText().trim();
      BufferedWriter out = new BufferedWriter(new FileWriter(f));
      out.write("PlayerNr=" + (settings.playerNr + 1) + "\n");
      out.write("GameName=" + settings.gameName + "\n");
      out.write("GameDir=" + settings.directory + "\n");
      out.flush();
      out.close();
      return settings;
    }