我有两个有3列的csv文件。我必须阅读此内容并使用hashmap()
(多个散列图)进行比较。
列:
Name,Value, Address
aaa,1,sdasdasd
bbb,2,sadasdasd
ccc,3,dsadasds
代码:
public class CompareFile {
public static void main(String args[]) throws IOException {
//HashMap<String, String> File1 = new HashMap<String, String>();
String filepath1="D:\\XYZ\\File1.csv";
String filepath2="D:\\XYZ\\File2.csv";
HashMap<String, HashMap<String, String>> file1= new HashMap<String, HashMap<String, String>>();
HashMap<String, HashMap<String, String>> file2= new HashMap<String, HashMap<String, String>>();
CompareFile compareFile = new CompareFile();
file1=compareFile.readFileContents(filepath1);
file2=compareFile.readFileContents(filepath2);
//compareFile.CompareTwo(file1,file2);
}//
public HashMap<String, HashMap<String, String>> readFileContents(String file) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line=null;
String[] str=null;
HashMap<String, HashMap<String, String>> mapHashMap = new HashMap<String, HashMap<String, String>>();
while((line=bufferedReader.readLine())!=null)
{
str = line.split(",");
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(str[1], str[2]);
mapHashMap.put(str[0], hashMap);
}
for (Map.Entry<String, HashMap<String, String>> entry : mapHashMap.entrySet())
{
System.out.println(entry.getKey() + " " + entry.getValue());
}return mapHashMap;
}
public void CompareTwo(HashMap<String, HashMap<String, String>> file1,HashMap<String, HashMap<String, String>> file2)throws IOException {
{
for(Map.Entry<String, HashMap<String, String>> entry1:file1.entrySet())
{
String key1=entry1.getKey();
HashMap<String, String> value1=entry1.getValue();
for(Map.Entry<String, HashMap<String, String>> entry2:file2.entrySet())
{
String key2=entry2.getKey();
HashMap<String, String> value2=entry2.getValue();
if(key1==key2)
{
System.out.println(key2 + "\t" + value1 + "\t" + value2);
}
}//
}//
}//
}//
答案 0 :(得分:-1)
我认为您应该考虑如何设计解决方案。首先创建一些类来表示什么是Csv文件,csv文件中的每一行是什么,等等......
例如,创建一个名为“CsvFile”的java类,它将包含一些表示文件中数据的属性,这些属性可能是一些新的java类(例如“CsvRow”)......
要读取文件,请使用InputStreamReader java类来读取和加载文件。
File file = new File("C:/ ... ");
InputStream stream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(stream, "ISO-8859-1");
然后你可以循环:
reader.read();
像这样:
String contentFile;
char[] buffer = new char[10000];
int n;
while ((n = reader.read(buffer)) > 0) {
contentFile.append(buffer, 0, n);
}
reader.close();
这就是如何阅读您的文件并获取内容。但是你仍然需要将这个文件内容加载到你自己的类中。