Skip to content

Instantly share code, notes, and snippets.

@superfunc
Created December 10, 2014 23:42
Show Gist options
  • Save superfunc/f98c09be26f195f05ab6 to your computer and use it in GitHub Desktop.
Save superfunc/f98c09be26f195f05ab6 to your computer and use it in GitHub Desktop.
Java file io example
import java.io.BufferedReader;
import java.io.FileReader;
public class test {
public static void main(String[] args) {
// We must put bufferedIO type work in a try-catch block
// because it could throw an exception.
try {
// Create a new buffered reader object,
// remember that it takes in a file reader as an argument
// to its constructor, so we just place it right here in
// the parenthesis since we won't need to refer to the file
// reader again. We are passing this source file as the file
// to read.
BufferedReader reader = new BufferedReader(new FileReader("test.java"));
// Read the first line of input
String temp = reader.readLine();
// readline will return null if it is done reading the file.
// so we check against it to know when to end our loop.
while(temp != null) {
// this is where we look at the individual characters
// each line that we take in. Its a simple for loop.
// Strings are basically an array of characters, so we
// can look at their elements in a similar way.
//
// For this example, we will print out only the characters
// that are curly braces
for(int i = 0; i < temp.length(); i++) {
// Gets the character at position i in the
// current line.
char c = temp.charAt(i);
if(c == '}' || c == '{') {
System.out.println(c);
}
}
temp = reader.readLine();
}
} catch (Exception e) {
System.out.println("Failed to open the file!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment