public static void main(String[] args)
{
/* 如果文件存在,则删除;如果文件不存在,则创建 */
File f = new File("d:" + File.separator + "test.txt");
if (f.exists()) {
f.delete();
} else {
/**
* windows中的目录分隔符用“\”表示;
* 而Linux中的目录分隔符用“/”表示。
* 所以推荐使用File.separator,这样可以兼容两个操作系统
*/
try {
f.createNewFile(); /* 由于createNewFile方法使用了throw关键字声明,
所以必须使用try...catch进行异常处理 */
} catch (IOException e) {
e.printStackTrace();
}
}
/* 如果文件夹存在,则删除;如果文件夹不存在,则创建 */
File folder = new File("d:" + File.separator + "test");
if (folder.exists()) {
folder.delete();
} else {
folder.mkdir();
}
}
public static void main(String[] args) throws Exception {
//第1步,使用File类绑定一个文件
File f = new File("d:" + File.separator + "test.txt");
//第2步,准备好文件输出流对象
OutputStream out = null;
out = new FileOutputStream(f);
//第3步,进行实际的写操作
String str = "Hello World\n";
byte b[] = str.getBytes();
out.write(b);
//第4步,关闭输出流
out.close();
//追加新内容
out = new FileOutputStream(f, true); //此处表示在文件末尾追加内容
String str2 = "Add the new content!\n";
byte b2[] = str2.getBytes();
out.write(b2);
out.close();
}
public static void main(String[] args) throws Exception {
//第1步,使用File类绑定一个文件
File f = new File("d:" + File.separator + "test.txt");
//第2步,准备好文件输入流对象
InputStream in = null;
in = new FileInputStream(f);
//第3步,进行实际的读操作
byte b[] = new byte[(int)f.length()]; //所有的内容读到此数组中,数组大小由文件决定
int len = in.read(b); //将内容读出,并且返回内容的长度
//第4步,关闭输入流
in.close();
System.out.println("内容为:\n" + new String(b, 0, len));
}
public static void main(String[] args) throws Exception {
//第1步,使用File类绑定一个文件
File f = new File("d:" + File.separator + "test.txt");
//第2步,准备好文件输入流对象
InputStream in = null;
in = new FileInputStream(f);
//第3步,进行实际的读操作
byte b[] = new byte[1024];
int temp = 0;
int len = 0;
while (-1 != (temp = in.read())) {
//将每次的读取内容赋值给temp变量,如果temp的值不是-1,表示文件没有读完
b[len] = (byte)temp;
len++;
}
//第4步,关闭输入流
in.close();
System.out.println("内容为:\n" + new String(b, 0, len));
}