Skip to content

Instantly share code, notes, and snippets.

@rbtr
Last active August 29, 2015 14:19
Show Gist options
  • Save rbtr/21fafb3209747ba5be48 to your computer and use it in GitHub Desktop.
Save rbtr/21fafb3209747ba5be48 to your computer and use it in GitHub Desktop.
FIO Hello World for workshop
package csc171.workshop;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException {
// P1
writeHelloWorld();
readHelloWorld();
// P2
writeHelloWorldSafely();
readHelloWorldSafely();
}
public static void writeHelloWorld() throws IOException, FileNotFoundException {
String filename = "abc.txt";
File file = new File(filename);
OutputStream os = null;
os = new FileOutputStream(file);
os.write("Hello World!".getBytes());
os.close();
}
public static void readHelloWorld() throws IOException, FileNotFoundException {
String filename = "abc.txt";
File file = new File(filename);
InputStream is = null;
is = new FileInputStream(file);
StringBuilder sb = new StringBuilder();
int d = 64;
while (d >= 64) {
byte[] data = new byte[d];
d = is.read(data, 0, 64);
sb.append(new String(data));
}
System.out.println(sb);
is.close();
}
public static void writeHelloWorldSafely() {
String filename = "abc.txt";
File file = new File(filename);
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write("Hello World!".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeSafely(os);
}
}
public static void readHelloWorldSafely() {
String filename = "abc.txt";
File file = new File(filename);
InputStream is = null;
try {
is = new FileInputStream(file);
StringBuilder sb = new StringBuilder();
int d = 64;
while (d >= 64) {
byte[] data = new byte[d];
d = is.read(data, 0, 64);
sb.append(new String(data));
}
System.out.println(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeSafely(is);
}
}
public static void closeSafely(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
// Squash
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment