Skip to content

Instantly share code, notes, and snippets.

@kencharos
Created May 15, 2013 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kencharos/5581622 to your computer and use it in GitHub Desktop.
Save kencharos/5581622 to your computer and use it in GitHub Desktop.
java File IO, std in example
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JavaSnippets {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// string to list
List<String> list = Arrays.asList("0","2","3");
list = Arrays.asList("0,1,2".split(","));
}
// read stdIO on java7
public static List<String> readStdIo() throws IOException {
List<String> input = new ArrayList<String>();
try (BufferedReader r = new BufferedReader(new InputStreamReader(System.in))) {
String line = r.readLine();
while (line != null) {
input.add(line);
line = r.readLine();
}
}
return input;
}
/** read file on java7 */
public static List<String> readFile(String name) throws IOException {
FileSystem fs = FileSystems.getDefault();
try {
return Files.readAllLines(fs.getPath(name), Charset.defaultCharset());
} catch (IOException e) {
throw e;
}
}
/** write file on java7 */
public static void writeFile(String name, List<String> data) throws IOException{
FileSystem fs = FileSystems.getDefault();
Path path = fs.getPath(name);
try (BufferedWriter out = Files.newBufferedWriter(path, Charset.defaultCharset())) {
for (String line : data) {
out.write(line);
out.newLine();
}
} catch (IOException e) {
throw e;
}
}
/** read file under java6 */
public static List<String> readFileOld(String name) throws IOException {
List<String> list = new ArrayList<>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(name), Charset.defaultCharset()));
String line;
while ((line = br.readLine()) != null) {
list.add(line);
}
} catch (IOException e) {
throw e;
} finally {
if (br != null) {
br.close();
}
}
return list;
}
/** write file under java6 */
public static void writeFileOld(String name, List<String> data) throws IOException{
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name), Charset.defaultCharset()));
for (String line : data) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
throw e;
} finally {
if (bw != null) {
bw.close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment