您的位置:首页 > 编程语言 > Java开发

【Java学习笔记】基础知识学习17【文件文本读取写入】

2013-07-26 23:37 691 查看
我们写程序,就自然涉及到从文件中读取文本,或者将生成的文本内容输入到文件。

这里介绍几种方法来完成我们需要的功能

文件读取:

文件读取需要使用的一个类是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
}
}


使用这个可以达到写入内容到文件的目的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐