在Java中,設置分隔符通常是指在使用某些庫或框架時,指定輸入或輸出的分隔符。以下是一些常見情況下如何設置Java分隔符的示例:
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();
}
}
}
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();
}
}
}
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);
}
}
}