public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
URL url = ClassLoader.getSystemClassLoader().getResource("./");
File file =new File(url.getPath());
File parentFile =new File(file.getParent());
File directory = new File("");//参数为空
String courseFile = directory.getCanonicalPath() ;
System.out.println(courseFile);
//源地址
File fileStations = new File(parentFile.getParent() + "\\stations.txt");
//写入文件地址
File fileCopy = new File(parentFile.getParent() + "\\subway8.txt");
BufferedReader br = null;
BufferedWriter bw = null;
try {
//如果文件不存在就创建
if (!(fileCopy.exists())) {
fileCopy.createNewFile();
}
br = new BufferedReader(new FileReader(parentFile.getParent() + "\\stations.txt"));
bw = new BufferedWriter(new FileWriter(parentFile.getParent() + "\\subway8.txt"));
String str = "";
int i = 1;
while((str = br.readLine()) != null){
bw.write(i+"="+str);
bw.newLine();
i++;
}
bw.flush(); //此处很关键,如果不写该语句,是不能从缓冲区写到文件里的
bw.close();
br.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
String filename = parentFile.getParent() + "\\subway8.txt";
Map<String, String> filemaps = readTxtFile(filename);
for (Map.Entry<String, String> entry : filemaps.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
public static Map<String,String> readTxtFile(String filePath) {
//存放内容的map对象
Map<String,String> filemaps = new HashMap<String,String>();
try {
String encoding = "UTF-8";
File file = new File(filePath);
//System.out.println(filePath);
int count = 0;//定义顺序变量
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {//按行读取
if(!"".equals(lineTxt)){
String reds = lineTxt.split("\\+")[0];//对行的内容进行分析处理后再放入map里。
int i = reds.indexOf("=");
reds = reds.substring(1, i)+reds.substring(i+1);
//System.out.println(reds);
filemaps.put("第"+count+"站", reds);//放入map
count ++;
}
}
read.close();//关闭InputStreamReader
bufferedReader.close();//关闭BufferedReader
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return filemaps;
}
IO流读取写入文件,通过map遍历
最新推荐文章于 2023-06-15 14:25:55 发布