Цитата(kornata @ 20.4.2010, 19:38 ) | | Это какие? |
http://opencsv.sourceforge.net/
| Код | import au.com.bytecode.opencsv.CSVReader;
import java.io.*;
public class CSVProcessor { public static void main(String[] args) { process(new File("C:\\TEMP\\Sample.csv"), new File("C:\\TEMP\\Sample.txt"), 50); }
public static void process(File inFile, File outFile, int width) { CSVReader csvReader = null; PrintWriter writer = null; try { writer = new PrintWriter(outFile); csvReader = new CSVReader(new FileReader(inFile), ',', '"'); String[] line; while((line = csvReader.readNext()) != null) { for(String col : line) { writer.write(pad(col, width)); } writer.println(); } } catch(IOException e) { e.printStackTrace(); } finally { close(csvReader); close(writer); } }
private static String pad(String col, int width) { col = col.trim(); if(isNumber(col)) { return padRight(col, width); } else { return padLeft(col, width); } }
private static String padRight(String col, int width) { if(col.length() > width) { return ' ' + col.substring(0, width) + ' '; } else { StringBuilder buffer = new StringBuilder(width + 2); buffer.append(' '); int i = width - col.length(); while(i > 0) { buffer.append(' '); i--; } buffer.append(col); buffer.append(' '); return buffer.toString(); } }
private static String padLeft(String col, int width) { if(col.length() > width) { return ' ' + col.substring(0, width) + ' '; } else { StringBuilder buffer = new StringBuilder(width + 2); buffer.append(' '); buffer.append(col); int i = width - col.length(); while(i > 0) { buffer.append(' '); i--; } buffer.append(' '); return buffer.toString(); } }
private static boolean isNumber(String col) { try { Double.parseDouble(col); return true; } catch(NumberFormatException e) { return false; } }
private static void close(Closeable closeable) { try { if(closeable != null) { closeable.close(); } } catch(IOException e) { e.printStackTrace(); } } }
|
|