1.适配源类:java.util.Properties
2.适配目标类:FileIO
3.适配器 FileProperties
package fileio;import java.io.IOException;public interface FileIO {public void readFromFile(String fileName) throws IOException;public void writeToFile(String fileName) throws IOException;public void setValue(String key , String value);public String getValue(String key); }
package fileio;import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties;public class FileProperties implements FileIO {private Properties p;public FileProperties(Properties p) {this.p = p;}@Overridepublic void readFromFile(String fileName) throws IOException {p.load(new FileInputStream(new File(fileName)));}@Overridepublic void writeToFile(String fileName) throws IOException {p.store(new FileOutputStream(new File(fileName)), "");}@Overridepublic void setValue(String key, String value) {p.setProperty(key, value);}@Overridepublic String getValue(String key) {return p.getProperty(key);}}
package fileio;import java.io.IOException; import java.util.Properties;public class Client {public static void main(String[] args) {FileIO fi = new FileProperties(new Properties());try {fi.readFromFile("test.txt");fi.setValue("name", "tisa");fi.setValue("age", "12");fi.setValue("school", "CCNU");fi.writeToFile("out.txt");} catch (IOException e) {e.printStackTrace();}} }