一、问题描述
输入文件内容和文件名称,将文件保存。使用工厂设计模式实现。
二、代码
1、文件服务接口
package io.train.fileservice;
/**
* 文件服务接口
* @Author Xlu
* @Date 15:20 2020-06-06
* @ClassName IFileService
**/
public interface IFileService {
//默认的目录
public static final String FILEDIR=new String("D:/xlu/");
public boolean saveFile();
}
2、文件服务实现类
package io.train.fileservice;
import io.train.serviceutil.InputUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
/**
* @ClassName: FileServiceImpl
* @Author: Xlu103
* @Date: 2020-06-06 15:19
**/
public class FileServiceImpl implements IFileService{
//静态方法块优先执行
static {
File fileDir=new File(IFileService.FILEDIR);
//如果目录为空,则创建目录
if (!fileDir.exists()) {
fileDir.mkdirs();
}
}
@Override
public boolean saveFile() {
InputUtil inputUtil = new InputUtil();
String content = inputUtil.getString("请输入内容:");
String fileName = inputUtil.getString("请输入文件名");
File desFile = new File(IFileService.FILEDIR+fileName);
PrintWriter out = null;
try {
out = new PrintWriter(desFile);
out.println(content);
} catch (FileNotFoundException e) {
return false;
}finally {
if (out != null) {
out.close();
}
}
System.out.println("文件"+desFile.getParentFile());
return true;
}
}
3、接口对象获取工厂类
package io.train.fileservice;
/**
* @ClassName: FileServiceFactory
* @Author: Xlu103
* @Date: 2020-06-06 15:36
**/
public class FileServiceFactory {
private FileServiceFactory(){}
public static IFileService getFileServiceImpl() {
return new FileServiceImpl();
}
}
4、测试类
package io.train.fileservice;
/**
* @ClassName: Test
* @Author: Xlu103
* @Date: 2020-06-06 15:18
**/
public class Test {
public static void main(String[] args) {
IFileService fileImp= FileServiceFactory.getFileServiceImpl();
if (fileImp.saveFile()) {
System.out.println("保存成功!");
}else{
System.out.println("保存失败!");
}
}
}
5、公用的工具类
package io.train.serviceutil;
import java.util.Scanner;
/**
* 输入类
*
* @ClassName: InputNum
* @Author: Xlu103
* @Date: 2020-06-06 14:19
**/
public class InputUtil {
private final Scanner INPUT = new Scanner(System.in);
/**
* 用于输入数字,并判断是否为数字
* @Author xlu
* @Date 14:31 2020-06-06
* @Param
* @return
*/
public int getInt(){
boolean flag=true;
int num;
String inputStr;
System.out.println("请输入一个数字");
while(flag){
if ((inputStr = INPUT.next()).matches("\\d+")) {
flag=false;
num = Integer.parseInt(inputStr);
return num;
}else{
System.out.println("输入错误字符,请重新输入:");
}
}
return 0;
}
/**
* 返回一个字符串
* @Author xlu
* @Date 15:27 2020-06-06
* @Param 提示文字
* @return 返回获得的字符串
*/
public String getString(String str){
System.out.println(str);
return INPUT.next();
}
}