文件
读文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ThreadTest {
public static void main(String[] args) {
File file = new File("D:\\新建文件夹\\test.txt");
FileInputStream fin = null;
byte[] words = new byte[3];
try {
fin = new FileInputStream(file);
System.out.println("开始读文件:");
int n = fin.read(words);
while (n != -1) {
System.out.println("此次读了" + n + "个字节,内容为:" + new String(words, 0, n));
n = fin.read(words);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
System.out.println("关闭读文件!");
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
写文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ThreadTest {
public static void main(String[] args) {
File file = new File("D:\\新建文件夹\\test.txt");
FileOutputStream fs = null;
try {
fs = new FileOutputStream(file, true);
String sayword = "天行健,君子以自强不息!";
System.out.println("开始写文件,其内容为:" + sayword);
fs.write(sayword.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fs != null) {
try {
System.out.println("关闭写文件!");
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}