Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Last active February 29, 2016 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/324ac60b46d2c318427d to your computer and use it in GitHub Desktop.
Save Cartman0/324ac60b46d2c318427d to your computer and use it in GitHub Desktop.
Java のPrintWriter とScanner を使ったCSVファイルの入出力(ReaderとWriter)
package csvwriterreader;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class CSVPrintWriter {
PrintWriter pw_;
// Constructor
public CSVPrintWriter(String fileName) {
try {
this.pw_ = new PrintWriter(fileName);
} catch (FileNotFoundException fnex) {
fnex.printStackTrace();
}
}
public CSVPrintWriter(File file) {
try {
this.pw_ = new PrintWriter(file);
} catch (FileNotFoundException fnex) {
fnex.printStackTrace();
}
}
public void close() {
this.pw_.close();
}
public void print(Object arg) {
synchronized (this.pw_) {
this.pw_.print(arg);
this.pw_.print(",");
}
}
public void println(Object... args) {
synchronized (this.pw_) {
for (int i = 0; i < args.length; i++) {
this.pw_.print(args[i]);
this.pw_.print(",");
}
this.pw_.println();
}
}
}
package csvwriterreader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Scanner;
public class CSVScanner {
Scanner scan_;
// Constructor
public CSVScanner(File source) {
try {
this.scan_ = new Scanner(source);
} catch (FileNotFoundException fnex) {
fnex.printStackTrace();
}
}
public CSVScanner(String source) {
this.scan_ = new Scanner(source);
}
public CSVScanner(InputStream source) {
this.scan_ = new Scanner(source);
}
public ArrayList<String[]> read() {
ArrayList<String[]> csv_list = new ArrayList<>();
String[] line_str_arr;
synchronized (this.scan_) {
while (this.scan_.hasNext()) {
line_str_arr = this.scan_.nextLine().split(",");
csv_list.add(line_str_arr);
}
}
return csv_list;
}
public void close() {
this.scan_.close();
}
}
package csvwriterreader;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class CSVWriterReader {
/**
* main
* @param args the command line arguments
*/
public static void main(String[] args) {
String file_name = "test.csv";
{
/*write CSV*/
CSVPrintWriter csvpw = new CSVPrintWriter(file_name);
csvpw.println(100, "Sato");
csvpw.println(101, "Suzuki");
csvpw.println(102, "Tanaka");
csvpw.close();
}
{
/*read CSV*/
CSVScanner csvscan = new CSVScanner(new File(file_name));
ArrayList<String[]> csv_data = csvscan.read();
csv_data.stream().forEach(
line->System.out.println(Arrays.toString(line))
);
csvscan.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment