Skip to content

Instantly share code, notes, and snippets.

@benjjo
Last active April 21, 2020 21:50
Show Gist options
  • Save benjjo/a4643651774d7632c1a3718a5db02682 to your computer and use it in GitHub Desktop.
Save benjjo/a4643651774d7632c1a3718a5db02682 to your computer and use it in GitHub Desktop.
Example of a buffered file reader using a buffered scanner.
/**
* Extracts comma separated values from an external file. The method readObjectData()
* expects to find employee data on each line separated by a comma. The pattern example outlined here:
*
* String,int,String,int
* String,int,String,int
*
* The above csv inputs are returned by Scanner as:
* - Name of employee (String)
* - Years employed (int)
* - Employee prodict code (String)
* - Number of sales (int)
*/
public void readObjectData()
{
String pathName = FileChooser.getFilename(); //Find a file chooser and change this
File aFile = new File(pathName);
Scanner bufferedScanner = null;
Object aObject;
try
{
String currentLine;
Scanner lineScanner;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while(bufferedScanner.hasNextLine())
{
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
aObject = new Object(lineScanner.next());
aObject.setYears(lineScanner.nextInt());
aObject.setProductCode(lineScanner.next());
aObject.setSales(lineScanner.nextInt());
aObject.setBonus(this.computeBonus(aObject));
this.getObjectsList().add(aObject);
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedScanner.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment