我们写程序,就自然涉及到从文件中读取文本,或者将生成的文本内容输入到文件。
这里介绍几种方法来完成我们需要的功能
文件读取:
文件读取需要使用的一个类是File,一个类是FileInputStream(文件字节输入流)类
使用方法如下代码所示:
static void FileRead(){
File txtFile=new File("G:\\logic.txt");
byte[] js=new byte[(int)(txtFile.length())];
try {
FileInputStream txtInput=new FileInputStream(txtFile);
txtInput.read(js);
String nTxt=new String(js);
System.out.println(nTxt);
} catch (Exception e) {
// TODO: handle exception
}
}
还可以使用FileReader(文件字符输入流)类来实现文本的读取。
static void FileReader(){
File txtFile=new File("G:\\logic.txt");
char[] js=new char[(int)(txtFile.length())];
try {
java.io.FileReader fRead=new java.io.FileReader(txtFile);
try {
fRead.read(js);
String kkk=new String(js);
System.out.println(kkk);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
文件写入:
使用FileOutputStream(文件字节输出流)类,加上File类辅助。
代码如下:
static void CreatText(){
File newFile=new File("G:\\re.txt");
try {
if(!newFile.exists()){
newFile.createNewFile();
}
FileOutputStream outS=new FileOutputStream(newFile);
byte[] buts="we are the world".getBytes();
outS.write(buts);
outS.close();
} catch (Exception e) {
// TODO: handle exception
}
}
再就是FileWriter文件字符输出流类:
static void CreatTextChar() {
File newFile = new File("G:\\re.txt");
try {
if (!newFile.exists()) {
newFile.createNewFile();
}
FileWriter outS = new FileWriter(newFile);
char[] buts = "we are the world".toCharArray();
outS.write(buts);
for (char c : buts) {
outS.append(c);
}
outS.close();
} catch (Exception e) {
// TODO: handle exception
}
}
使用这个可以达到写入内容到文件的目的。