/* 1、创建File类的对象
2、File.createFile() 方法创建新文件,若文件已经存在则返回false,创建成功返回true
3、使用FileInputStream读取文件文件内容,使用BufferedInputStream加速读取
4、无论上述步骤成功与否都要最后关闭相关的streams,在finally语句中关闭
*/
import java.io.*;
public class Exercise {
public static void main(String args[]) {
try {
File file = new File("/home/zjz/Desktop/newFile.txt");
/* If file gets created then the createNewFile(),
method would return true or if the file is already present,
it would return false
*/
boolean fvar = file.createNewFile();
if (fvar) {
System.out.println("File has been created successfully.");
} else {
System.out.println("File already present at the specified location");
}
} catch (IOException e) {
System.out.println("Exception Occurred: ");
e.printStackTrace();
}
try {
File file = new File("/home/zjz/Desktop/newFile.txt");
/* The delete() method returns true if the file is
deleted successfully else it returns false
*/
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete failed: File didn't delete successfully");
}
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
File file = new File("/home/zjz/Desktop/newFile.txt");
BufferedInputStream bis = null;
FileInputStream fis = null;
try {
// FileInputStream to read the file
fis = new FileInputStream(file);
/* Passed the FileInputStream to BufferedInputStream
for Fast read using the buffer array.
*/
bis = new BufferedInputStream(fis);
/* available() method of BufferedInputStream
returns 0 when there are no more bytes present in
the file to be read.
*/
while (bis.available() > 0) {
System.out.print((char) bis.read());
}
} catch (FileNotFoundException fnfe) {
System.out.println("The specified file not found");
} catch (IOException ioe) {
System.out.println("I/O Exception: " + ioe);
} finally {
try {
if (bis != null && fis != null) {
fis.close();
bis.close();
}
} catch (IOException ioe) {
System.out.println("Error in InputStream close(): " + ioe);
}
}
}
}
From: http://beginnersbook.com/2014/01/how-to-write-to-a-file-in-java-using-fileoutputstream/