Module Server : ajout clss FileUtil, ajout vérif existance fichier dans clss FileStockDao

This commit is contained in:
Notmoo 2017-07-30 14:07:50 +02:00
parent 60935bf45e
commit 57757fe10b
2 changed files with 42 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package com.pqt.server.module.stock;
import com.pqt.core.entities.product.Product;
import com.pqt.server.utils.FileUtil;
import java.io.*;
import java.util.*;
@ -82,6 +83,15 @@ public class FileStockDao implements IStockDao {
private Map<Long, Product> load(){
Map<Long, Product> loadedData = new HashMap<>();
try{
if(FileUtil.createFileIfNotExist(STOCK_FILE_NAME)){
return loadedData;
}
}catch(IOException e){
e.printStackTrace();
return loadedData;
}
try(FileInputStream fis = new FileInputStream(STOCK_FILE_NAME);
ObjectInputStream ois = new ObjectInputStream(fis)){
@ -106,6 +116,12 @@ public class FileStockDao implements IStockDao {
}
private void save(Map<Long, Product> products){
try{
FileUtil.createFileIfNotExist(STOCK_FILE_NAME);
}catch (IOException e){
e.printStackTrace();
return;
}
try(FileOutputStream fos = new FileOutputStream(STOCK_FILE_NAME);
ObjectOutputStream oos = new ObjectOutputStream(fos)){

View File

@ -0,0 +1,26 @@
package com.pqt.server.utils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileUtil {
/**
* Check if the given file path correspond to an existing file, and create it if it doesn't.
*
* @param filePath the file path to check
*
* @return {@code true} if the file has been created, {@code false} if it already existed.
* @throws IOException if any IOException happend during this method's execution.
*/
public static boolean createFileIfNotExist(String filePath) throws IOException {
Path path = Paths.get(filePath);
if(!Files.exists(path)){
Files.createFile(path);
return true;
}
return false;
}
}