阅读量:0
在Java中,设置分隔符通常是指在使用某些库或框架时,指定输入或输出的分隔符。以下是一些常见情况下如何设置Java分隔符的示例:
- 使用Scanner类读取CSV文件:
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { try { File file = new File("example.csv"); Scanner scanner = new Scanner(file); String line = scanner.nextLine(); StringTokenizer st = new StringTokenizer(line, ","); // 设置分隔符为逗号 while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
- 使用Apache Commons CSV库读取CSV文件:
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.FileReader; import java.io.IOException; import java.nio.file.Paths; public class Main { public static void main(String[] args) { try (CSVParser parser = new CSVParser(new FileReader("example.csv"), CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim())) { for (CSVRecord record : parser) { System.out.println(record.toMap()); } } catch (IOException e) { e.printStackTrace(); } } }
- 使用Java内置的String类方法分割字符串:
public class Main { public static void main(String[] args) { String input = "Hello,World,Java,Programming"; String[] tokens = input.split(","); // 设置分隔符为逗号 for (String token : tokens) { System.out.println(token); } } }