刚接触多态和接口,很是迷茫,希望大虾们多指点啊
题目如下:
输入输出接口IOEquip,定义两方法输入和输出;两个类Display,Keyboard实现接口,在控制台通过键盘类输入信息并保存到硬盘Disk类,之后从硬盘把信息读出来通过显示器类输出.创建Computer类实现以上属性和方法.
------解决方案--------------------
我写了一个,跟你的要求貌似有点出入
public interface IOEquip {
/**
*
* 文件写入磁盘
* @param fileName
* @throws Exception
*/
void outputAndSave(String fileName) throws Exception;
/**
*
* 文件读取
* @param fileName
* @throws Exception
*/
void readAndInput(String fileName) throws Exception;
}
public class Computer implements IOEquip {
@Override
public void outputAndSave(String fileName) throws Exception{
File outputFile = new File(fileName);//创建文件
if(!outputFile.exists()){
outputFile.createNewFile();
}
//控制台输入字符串
Scanner s = new Scanner(System.in);
System.out.println("请输入字符串!");
String str = s.nextLine();
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)), true);
if(str != null && str.length() > 0){
pw.print(str);
}else{
pw.println("你好,你没有在控制台输入任何字符!");
}
pw.close();
s.close();
}
@Override
public void readAndInput(String fileName) throws Exception{
BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
String line;
while((line = in.readLine())!= null){
System.out.println(line);
}
in.close();
}
public static void main(String[] args) throws Exception {
Computer c = new Computer();
c.readAndInput("E:\\123");
}
}