Das Beispiel CvsTool:Javakurs
Version vom 26. Oktober 2014, 22:31 Uhr von Hamatoma (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „Category:Tutorial Category:Java <pre><code> import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader;…“)
<code> import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CsvTool { String lines[] = null; String name; String separator = ";"; public String[] readFile(final String filename) throws IOException { final int count = countLines(filename); final String lines[] = new String[count]; final File file = new File(filename); final BufferedReader reader = new BufferedReader(new FileReader(file)); String line; int ix = 0; while (ix < count && (line = reader.readLine()) != null) lines[ix++] = line; reader.close(); return lines; } public void writeFile(final String filename) throws IOException { final BufferedWriter writer = new BufferedWriter(new FileWriter( new File(filename))); for (int ix = 0; ix < this.lines.length; ix++) writer.write(this.lines[ix] + "\n"); writer.close(); } public int countLines(final String filename) throws IOException { int count = 0; final File file = new File(filename); final BufferedReader reader = new BufferedReader(new FileReader(file)); while (reader.readLine() != null) count++; reader.close(); return count; } public String getCol(final int lineNo, final int col) { String rc = null; if (lineNo >= 0 && lineNo < this.lines.length) { final String line = this.lines[lineNo]; final String[] cols = line.split(this.separator); if (col >= 0 && col < cols.length) rc = cols[col]; } return rc; } public void setCol(final int lineNo, final int col, final String value) { if (col >= 0 && lineNo >= 0 && lineNo < this.lines.length) { String line = this.lines[lineNo]; final int count = countCols(line); if (count < col){ final String[] cols = line.split(line); cols[col] = value; this.lines[lineNo] = join(cols); } else { for (int ix = count; ix < col; ix++) line = line + this.separator; this.lines[lineNo] = line + value; } } } public int countCols(final String line) { int rc = 0; int ix = 0; while ((ix = line.indexOf(this.separator, ix)) > 0) rc++; return rc; } public String join(final String[] cols) { final StringBuilder buffer = new StringBuilder(); for (int ix = 0; ix < cols.length; ix++) { if (ix > 0) buffer.append(this.separator); buffer.append(cols[ix]); } return buffer.toString(); } public static void main(final String[] args) { String fname = "test.csv"; if (args.length > 0) fname = args[0]; final CsvTool tool = new CsvTool(); try { tool.readFile(fname); } catch (final IOException e) { e.printStackTrace(); } } } </code>