1
來讀取資源目錄CSV文件JUnit測試裏面有一個標準的Maven項目的資源目錄csv文件,如下所示:如何使用文件實用程序
src/main/resources/fruits.csv
src/test/resources/fruits.csv
fruits.csv
Type, Quantity
apple, 50
banana, 60
orange, 70
使用以下庫
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
水果(標準POJO)
public class Fruit {
private String type
private int quantity;
public Fruit(String type, int quantity) {
this.type = type;
this.quantity = quantity;
}
// Getters & Setters
}
CsvFileReader
public class CsvFileReader {
private static final String [] FILE_HEADER = {""};
private static final String TYPE = "Type";
private static final String QUANTITY + "Quantity";
public static List<Candidate> readCsvFile(File fileName) {
FileReader fileReader = null;
CSVParser csvFileParser = null;
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER);
List<Candidate> fruits = null;
try {
fruits = new ArrayList<>();
String file = FileUtils.readFileToString(fileName);
fileReader = new FileReader(file);
csvFileParser = new CSVParser(fileReader, csvFormat);
List<CSVRecord> records = csvFileParser.getRecords();
for (int i = 1; i < records.size(); i++) {
CSVRecord record = records.get(i);
Fruit fruit = new Fruit(record.get(TYPE), Integer.parseInt(QUANTITY));
fruits.add(fruit);
}
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try {
fileReader.close();
csvFileParser.close();
} catch(IOException e) {
e.printStackTrace();
}
}
return fruits;
}
}
CsvFileReaderTest(JUnit 4測試案例):
public class CsvFileReaderTest {
File csvFile = null;
@Before
public void setUp() throws Exception {
String userDir = System.getProperty("user.dir");
String filePath = userDir + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
csvFile = FileUtils.getFile(filePath + "fruits.csv");
}
}
當我運行在Eclipse中JUnit測試案例:
java.io.FileNotFoundException: Type, Quantity
apple, 50
banana, 60
orange, 70
(File name too long)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
這似乎讀文件,但問題是FileName太長?
我在做什麼錯?
src下文件存儲的整點/主/資源(或者src/test/resources)是讓該文件在運行時(resp.test)類路徑中作爲資源可用,並且可以使用ClassLoader加載它。使用'SomeClass.class.getResourceAsStream(「/ fruits.csv」)'獲取資源上的InputStream。不要使用文件IO。 –
我認爲POJO只是一個例子,對吧?因爲構造函數缺少第二個參數 – Vogel612
Vogel612的類型 - 謝謝指出 - 我做了適當的編輯。 @JB Nizet,你是說我應該通過maven運行JUnit測試,而不是通過Eclipse運行它? –