Skip to content

Instantly share code, notes, and snippets.

@tomoTaka01
Created February 18, 2012 10:25
Show Gist options
  • Save tomoTaka01/1858634 to your computer and use it in GitHub Desktop.
Save tomoTaka01/1858634 to your computer and use it in GitHub Desktop.
tomoTaka01:read text file(key,value) and make treeMap
/**
* text file(key , value) -> TreeMap
* without charest
* @return
*/
private static Map<String, String> getMapFromTxt1() {
Map<String, String> map = new TreeMap<String, String>();
String path = new File(getPath()).getParent();
StringBuilder sb = new StringBuilder();
sb.append(path).append(File.separator).append("xxx.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(sb.toString()));
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
// System.out.println("line=" + line);
String[] values = line.split(",");
map.put(values[0], values[1]);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ReadText.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ReadText.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {}
}
}
return map;
}
/**
* text file(key , value) -> TreeMap
* with charest
* @return
*/
private static Map<String, String> getMapFromTxt2() {
Map<String, String> map = new TreeMap<String, String>();
String path = new File(getPath()).getParent().toString();
StringBuilder sb = new StringBuilder();
sb.append(path).append(File.separator).append("xxx.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(sb.toString()), "UTF-8"));
for (String line = reader.readLine(); line != null; line = reader.readLine()){
String[] values = line.split(",");
map.put(values[0], values[1]);
}
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(ReadText.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(ReadText.class.getName()).log(Level.SEVERE, null, ex);
}catch (IOException ex) {
Logger.getLogger(ReadText.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (reader != null){
try {
reader.close();
} catch (IOException ex) {}
}
}
return map;
}
/**
* get path
* @return path
*/
private static String getPath() {
return "/Users/tomo/test1/test2/test3";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment