Java Code Examples for java.io.RandomAccessFile.readLine()

The following are Jave code examples for showing how to use readLine() of the java.io.RandomAccessFile class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: spring2017java   File: FileIODemoSection3.java   Source Code and License Vote up 7 votes
public void readFromFileUsingLoop() {
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile("input.txt", "r");
        String line;

        while (true) {
            line = randomAccessFile.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
        }

    } catch (FileNotFoundException fnfe) {
        System.out.println("Could not find the input file");
    } catch (IOException ioe) {
        System.out.println("Can't read anymore!");
    }

}
 
Example 2
Project: sumo   File: ThumbnailsImageReader.java   Source Code and License Vote up 6 votes
private void parsePTS(File pts) {
    try {
        RandomAccessFile temp = new RandomAccessFile(pts, "r");
        String line = null;
        this.gcps = new ArrayList<Gcp>();
        while ((line = temp.readLine()) != null) {
            String[] nums = line.split(" ");
            if (nums.length == 4) {
                Gcp gcp = new Gcp();
                gcp.setXgeo(Double.parseDouble(nums[0]));
                gcp.setYgeo(Double.parseDouble(nums[1]));
                gcp.setXpix(Double.parseDouble(nums[2]));
                gcp.setYpix(Double.parseDouble(nums[3]));
                gcps.add(gcp);
            }
        }
        temp.close();
    } catch (Exception ex) {
    	logger.error(ex.getMessage(),ex);
    }
}
 
Example 3
Project: sumo   File: GeotiffImage.java   Source Code and License Vote up 6 votes
private void parsePTS(File pts) {
    try {
        RandomAccessFile temp = new RandomAccessFile(pts, "r");
        String line = null;
        this.gcps = new ArrayList<Gcp>();
        while ((line = temp.readLine()) != null) {
            String[] nums = line.split(" ");
            if (nums.length == 4) {
                Gcp gcp = new Gcp();
                gcp.setXgeo(Double.parseDouble(nums[0]));
                gcp.setYgeo(Double.parseDouble(nums[1]));
                gcp.setXpix(Double.parseDouble(nums[2]));
                gcp.setYpix(Double.parseDouble(nums[3]));
                gcps.add(gcp);
            }
        }
        temp.close();
    } catch (Exception ex) {
    	logger.error(ex.getMessage(),ex);
    }
}
 
Example 4
Project: spring2017java   File: FileIODemoSection3.java   Source Code and License Vote up 6 votes
public void readUsingRandomAccessFile() {
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile("input.txt", "r");
        int x = Integer.parseInt(randomAccessFile.readLine());
        double y = Double.parseDouble(randomAccessFile.readLine());
        String s = randomAccessFile.readLine();
        System.out.println(x);
        System.out.println(y);
        System.out.println(s);
    } catch (FileNotFoundException fnfe) {
        System.out.println("Could not find the input file");
    } catch (IOException ioe) {
        System.out.println("Can't read anymore!");
    }

}
 
Example 5
Project: can4eve   File: RandomAccessLogReader.java   Source Code and License Vote up 6 votes
/**
 * get the next Packet from the RandomAccessFile
 * 
 * @param raf
 * @return - the Packet
 * @throws Exception
 */
public PacketSeek nextPacket(RandomAccessFile raf) throws Exception {
  String line = null;
  int count = 0;
  long pos = raf.getFilePointer();
  while ((line = raf.readLine()) != null) {
    Packet p = LogReader.lineAsPacket(line);
    if (p != null) {
      PacketSeek packetSeek = new PacketSeek();
      packetSeek.packet = p;
      packetSeek.pos = pos;
      return packetSeek;
    }
    pos = raf.getFilePointer();
    if (checkCountLimit("line", count++, false))
      return null;
  } // while
  return null;
}
 
Example 6
Project: easyfilemanager   File: StorageUtils.java   Source Code and License Vote up 5 votes
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
   private long getSizeTotalRAM(boolean isTotal) {
	long sizeInBytes = 1000;
	MemoryInfo mi = new MemoryInfo();
	activityManager.getMemoryInfo(mi);
	if(isTotal) {
		try { 
			if(Utils.hasJellyBean()){
				long totalMegs = mi.totalMem;
				sizeInBytes = totalMegs;
			}
			else{
				RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
				String load = reader.readLine();
				String[] totrm = load.split(" kB");
				String[] trm = totrm[0].split(" ");
				sizeInBytes=Long.parseLong(trm[trm.length-1]);
				sizeInBytes=sizeInBytes*1024;
				reader.close();	
			}
		} 
		catch (Exception e) { }
	}
	else{
		long availableMegs = mi.availMem;
		sizeInBytes = availableMegs;
	}		
	return sizeInBytes;
}
 
Example 7
Project: ibench   File: iBench.java   Source Code and License Vote up 5 votes
public void parseConfigFile(String scenarioListFile) throws Exception {
	if (!new File(scenarioListFile).exists())
		throw new Exception(scenarioListFile + " does not exit");

	try {
		RandomAccessFile raf = new RandomAccessFile(scenarioListFile, "r");

		String line = "";
		while (line != null) {
			line = raf.readLine();

			if (line == null)
				break;
			if (line.startsWith("#"))
				continue;

			String trimmedLine = line.trim();
			if (trimmedLine.length() == 0)
				continue;

			run(trimmedLine);
		}

		raf.close();
	}
	catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 8
Project: spring2017java   File: MidtermExamSection4.java   Source Code and License Vote up 5 votes
public int countLines(String filename) {
    int count = 0;
    
    try {
        RandomAccessFile input = new RandomAccessFile(filename, "r");
        
        String line;
        while ((line = input.readLine()) != null) {
            count++;
        }
        
        /*
        while (true) {
            String line = input.readLine();
            if (line == null)
                break;
            count++;
        }
        */
    } catch (FileNotFoundException fnfe) {

    } catch (IOException ioe) {
        
    }
    
    return count;
}
 
Example 9
Project: FireFiles   File: StorageUtils.java   Source Code and License Vote up 5 votes
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
   private long getSizeTotalRAM(boolean isTotal) {
	long sizeInBytes = 1000;
	MemoryInfo mi = new MemoryInfo();
	activityManager.getMemoryInfo(mi);
	if(isTotal) {
		try { 
			if(Utils.hasJellyBean()){
				long totalMegs = mi.totalMem;
				sizeInBytes = totalMegs;
			}
			else{
				RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
				String load = reader.readLine();
				String[] totrm = load.split(" kB");
				String[] trm = totrm[0].split(" ");
				sizeInBytes=Long.parseLong(trm[trm.length-1]);
				sizeInBytes=sizeInBytes*1024;
				reader.close();	
			}
		} 
		catch (Exception e) { }
	}
	else{
		long availableMegs = mi.availMem;
		sizeInBytes = availableMegs;
	}		
	return sizeInBytes;
}
 
Example 10
Project: simple-share-android   File: StorageUtils.java   Source Code and License Vote up 5 votes
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
   private long getSizeTotalRAM(boolean isTotal) {
	long sizeInBytes = 1000;
	MemoryInfo mi = new MemoryInfo();
	activityManager.getMemoryInfo(mi);
	if(isTotal) {
		try { 
			if(Utils.hasJellyBean()){
				long totalMegs = mi.totalMem;
				sizeInBytes = totalMegs;
			}
			else{
				RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
				String load = reader.readLine();
				String[] totrm = load.split(" kB");
				String[] trm = totrm[0].split(" ");
				sizeInBytes=Long.parseLong(trm[trm.length-1]);
				sizeInBytes=sizeInBytes*1024;
				reader.close();	
			}
		} 
		catch (Exception e) { }
	}
	else{
		long availableMegs = mi.availMem;
		sizeInBytes = availableMegs;
	}		
	return sizeInBytes;
}
 
Example 11
Project: hadoop   File: Storage.java   Source Code and License Vote up 5 votes
/**
 * Attempts to acquire an exclusive lock on the storage.
 * 
 * @return A lock object representing the newly-acquired lock or
 * <code>null</code> if storage is already locked.
 * @throws IOException if locking fails.
 */
@SuppressWarnings("resource")
FileLock tryLock() throws IOException {
  boolean deletionHookAdded = false;
  File lockF = new File(root, STORAGE_FILE_LOCK);
  if (!lockF.exists()) {
    lockF.deleteOnExit();
    deletionHookAdded = true;
  }
  RandomAccessFile file = new RandomAccessFile(lockF, "rws");
  String jvmName = ManagementFactory.getRuntimeMXBean().getName();
  FileLock res = null;
  try {
    res = file.getChannel().tryLock();
    if (null == res) {
      throw new OverlappingFileLockException();
    }
    file.write(jvmName.getBytes(Charsets.UTF_8));
    LOG.info("Lock on " + lockF + " acquired by nodename " + jvmName);
  } catch(OverlappingFileLockException oe) {
    // Cannot read from the locked file on Windows.
    String lockingJvmName = Path.WINDOWS ? "" : (" " + file.readLine());
    LOG.error("It appears that another node " + lockingJvmName
        + " has already locked the storage directory: " + root, oe);
    file.close();
    return null;
  } catch(IOException e) {
    LOG.error("Failed to acquire lock on " + lockF
        + ". If this storage directory is mounted via NFS, " 
        + "ensure that the appropriate nfs lock services are running.", e);
    file.close();
    throw e;
  }
  if (!deletionHookAdded) {
    // If the file existed prior to our startup, we didn't
    // call deleteOnExit above. But since we successfully locked
    // the dir, we can take care of cleaning it up.
    lockF.deleteOnExit();
  }
  return res;
}
 
Example 12
Project: DeviceInfo   File: Methods.java   Source Code and License Vote up 5 votes
/**
 * Get max cpu rate.
 *
 * This works by examining the list of CPU frequencies in the pseudo file
 * "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state" and how much time has been spent
 * in each. It finds the highest non-zero time and assumes that is the maximum frequency (note
 * that sometimes frequencies higher than that which was designed can be reported.) So it is not
 * impossible that this method will return an incorrect CPU frequency.
 *
 * Also note that (obviously) this will not reflect different CPU cores with different
 * maximum speeds.
 *
 * @return cpu frequency in MHz
 */
public static int getMaxCPUFreqMHz() {

    int maxFreq = -1;
    try {

        RandomAccessFile reader = new RandomAccessFile( "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state", "r" );

        boolean done = false;
        while ( ! done ) {
            String line = reader.readLine();
            if ( null == line ) {
                done = true;
                break;
            }
            String[] splits = line.split( "\\s+" );
            assert ( splits.length == 2 );

            int timeInState = Integer.parseInt( splits[1] );
            if ( timeInState > 0 ) {
                int freq = Integer.parseInt( splits[0] ) / 1000;
                System.out.println("maxFreq = " + freq);
                if ( freq > maxFreq ) {
                    maxFreq = freq;
                }
            }
        }

    } catch ( IOException ex ) {
        ex.printStackTrace();
    }

    return maxFreq;
}
 
Example 13
Project: metanome-algorithms   File: RandomAccessSample.java   Source Code and License Vote up 4 votes
public static List<List<String>> getSample(FileInput input, long numSamples){
  input.getFileName();
  File file = new File(input.getFileName());
  long length = file.length();
  Set<List<String>> set = new HashSet<>();
  Random rnd = new Random();

  while (set.size() < numSamples) {
    try {
      RandomAccessFile rndFile = new RandomAccessFile(file, "r");
      long randomPosition = (long)(rnd.nextDouble()*(length));
      rndFile.seek(randomPosition);
      rndFile.readLine();
      String line = rndFile.readLine();
      if(line == null) continue;
      Reader in = new StringReader(line);
      CSVReader csvReader = new CSVReader(in,
                                          input.getSeparatorAsChar(),
                                          input.getQuoteCharAsChar(),
                                          input.getEscapeCharAsChar(),
                                          input.getSkipLines(),
                                          input.isStrictQuotes(),
                                          input.isIgnoreLeadingWhiteSpace());
      String[] values = csvReader.readNext();
      List<String> valueList = new ArrayList<>();
      for (String val : values) {
        if (val.equals("")) {
          valueList.add(null);
        } else {
          valueList.add(val);
        }
        if (!set.contains(valueList))
          set.add(valueList);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  //Todo: return value - + wrapper for interface compatibility
  return new ArrayList<>(set);
}
 
Example 14
Project: sumo   File: ConsoleLayer.java   Source Code and License Vote up 4 votes
public void runScript(String file) throws Exception {
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    String line = null;
    try{
     while ((line = raf.readLine()) != null) {
         String[] command = line.split(" ");
         for (String c : pl.getCommands()) {
             if (c.startsWith(command[0])) {
                 String[] args = new String[command.length - 1];
                 for (int i = 1; i < command.length; i++) {
                     args[i - 1] = command[i];
                 }
                 try {
                     Object a = pl.getActions().get(c);//Class.forName(actions.get(c).getClassName()).newInstance();
                     if (!(a instanceof IConsoleAction)) {
                         return;
                     }
                     SumoAbstractAction ica = (SumoAbstractAction) a;
                     //if (ica instanceof IProgressListener) {
                         currentAction = (SumoAbstractAction) ica;
                         if (ica.execute()) {
                             return;
                         }
                         while (currentAction != null && !currentAction.isDone()) {
                             Thread.sleep(1000);
                         }
                     /*} else {
                         if (!ica.execute()) {
                             return;
                         }
                     }*/
                 	return;
                 } catch (Exception e) {
                     e.printStackTrace();
                     return;
                 }
             }
         }
         Thread.sleep(1000);
     }
    }finally{
    	raf.close();
    }
}