使用FileOutputStream写入指定内容到指定文件
/**
* @author 南风知我意唔
* @version 1.0
* 使用FileOutputStream写入指定内容到指定文件
*/
public class DemoFileOutputStream {
public static void main(String[] args) {
while (true){
Scanner input=new Scanner(System.in);
//指定文件地址
System.out.print("FilePath:");
String filePath=input.nextLine();
//内容
System.out.print("Content:");
String message=input.nextLine();
boolean b = false;
try{
b=writeToLocalFile(message, filePath, true);
}catch (Exception e){
System.out.println(e.getMessage());
}
if (b){
System.out.println("success!");
}else{
System.out.println("fail!");
}
System.out.print("是否继续(y)添加:");
String y=input.nextLine();
if (!y.equals("y")){
System.out.println("系统退出....");
break;
}
}
}
public static boolean writeToLocalFile(String message,String filePath,boolean b){
File file=new File(filePath);
System.out.println(file);
System.out.println(filePath);
if (message==null){
throw new MessageIsNull("写入信息为null");
}
if (!file.exists()){
throw new FileException("路径不存在:"+filePath);
}
if (!file.isFile()){
throw new FileException("Not is File:"+filePath);
}
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(file,b);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] messages = message.getBytes();
try {
fileOutputStream.write(messages);
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
return false;
}finally {
if (fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
}
class FileException extends RuntimeException{
public FileException(String message) {
super(message);
}
}
class MessageIsNull extends RuntimeException{
public MessageIsNull(String message) {
super(message);
}
}