在Java编程中,处理平面文件是常见的需求,无论是文本文件、CSV文件还是XML文件,都是数据交换和存储的重要方式。本文将为你介绍如何在Java中轻松解析这些类型的平面文件,并提供一些实用的处理技巧。
文本文件处理
1. 使用java.io.BufferedReader
对于简单的文本文件,可以使用java.io.BufferedReader来逐行读取内容。以下是一个简单的例子:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TextFileReader {
public static void main(String[] args) {
String filePath = "example.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 使用正则表达式处理文本
Java中的java.util.regex包提供了强大的正则表达式处理能力。以下是一个使用正则表达式提取文本文件中特定信息的例子:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TextFileRegexExample {
public static void main(String[] args) {
String filePath = "example.txt";
String regex = "\\b\\w+\\b"; // 匹配单词
Pattern pattern = Pattern.compile(regex);
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
CSV文件处理
1. 使用Apache Commons CSV
Apache Commons CSV是一个Java库,可以方便地读取和写入CSV文件。以下是一个使用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;
public class CsvFileReader {
public static void main(String[] args) {
String filePath = "example.csv";
try (CSVParser parser = new CSVParser(new FileReader(filePath), CSVFormat.DEFAULT.withHeader())) {
for (CSVRecord record : parser) {
System.out.println(record.get("Column1") + ", " + record.get("Column2"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 使用Java 8的流式API
Java 8引入了流式API,可以用来简化CSV文件的处理。以下是一个使用Java 8流式API读取CSV文件的例子:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class CsvFileStreamExample {
public static void main(String[] args) {
String filePath = "example.csv";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StreamSupport.stream(new org.apache.commons.csv.CSVReader(br).spliterator(), false)
.forEach(record -> System.out.println(record.get(0) + ", " + record.get(1)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
XML文件处理
1. 使用DOM解析器
Java提供了DOM解析器来处理XML文件。以下是一个使用DOM解析器读取XML文件的例子:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class XmlFileDomExample {
public static void main(String[] args) {
String filePath = "example.xml";
try {
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("item");
for (int temp = 0; temp < nList.getLength(); temp++) {
Element element = (Element) nList.item(temp);
System.out.println("Name: " + element.getElementsByTagName("name").item(0).getTextContent());
}
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
2. 使用SAX解析器
SAX解析器是一种基于事件的解析器,适用于处理大型XML文件。以下是一个使用SAX解析器读取XML文件的例子:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class XmlFileSaxExample {
static String temp = "";
public static void main(String[] args) {
String filePath = "example.xml";
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("item")) {
temp = attributes.getValue("name");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("item")) {
System.out.println("Name: " + temp);
temp = "";
}
}
};
saxParser.parse(new File(filePath), handler);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
通过以上示例,你可以看到在Java中处理文本、CSV和XML文件的方法。每种文件格式都有其独特的处理方式,但基本的思路是相似的:读取文件内容,解析数据,然后进行相应的处理。希望这些例子能帮助你快速上手Java中的平面文件处理技巧。
