一、使用字符流,读取和存储纯文本文件。
存储文件,也就是像一个文件里写内容,既然是写,那就需要使用输出流。而且我们写的是纯文本文件,所以这里使用字符流来操作,java api提供给我们FileWriter这么一个类,我们来试试:(读取文件同理使用FileReader类)
package IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOcom {
public static void main(String[] args) throws Exception{
File f=new File("test.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("创建成功!");
}else{
//写 输人
FileWriter fw=new FileWriter(f);
fw.write("我想你了");
fw.flush();
fw.close();
//读 输出
FileReader fr=new FileReader(f);
char[] cr=new char[(int) f.length()];
String str = ""; // 用来将每次读取到的字符拼接,当然使用StringBuffer类更好
int n; // 每次读取到的字符长度
while ((n = fr.read(cr)) != -1) {
str += new String(cr, 0, n);
}
//fr.read(cr, 0, (int)f.length());
fr.close();
System.out.println(str);
}
writetoFile(new String("path.txt") , new String("我会做的更好的,请相信我!"));
readfromFile(new String("path.txt"));
}
/**
*
* @param path DOC 从文件里读取数据.
* @throws FileNotFoundException
* @throws IOException
*/
@SuppressWarnings("unused")
private static void readfromFile(String path) throws FileNotFoundException,IOException{
File file=new File(path);// 指定要读取的文件
FileReader fileReader=new FileReader(file);// 获取该文件的输入流
char [] c=new char[(int)file.length()];// 用来保存每次读取到的字符
int n =0;// 用来将每次读取到的字符拼接,当然使用StringBuffer类更好
String str="";// 每次读取到的字符长度
while((n=fileReader.read(c))!=-1){
str+=new String(c, 0, n);
}
fileReader.close();// 关闭输入流,释放连接
System.out.println(str);
}
/**
*
* @param path
* @param write
* @throws IOException
*/
@SuppressWarnings("unused")
private static void writetoFile(String path,String write) throws IOException{
File file=new File(path);// 要写入的文本文件
if(!file.exists()){// 如果文件不存在,则创建该文件
file.createNewFile();
}
FileWriter writer=new FileWriter(file); //获取该文件的输出流
writer.write(write);// 写内容
writer.flush();// 清空缓冲区,立即将输出流里的内容写到文件里
writer.close();// 关闭输出流,施放资源
}
@SuppressWarnings("unused")
private static void ImgtoFile(String topath,String frompath) throws FileNotFoundException,IOException{
FileInputStream fis=new FileInputStream(new File(topath));//指定图片的路径
File file=new File(frompath);
if(!file.exists()){//判断文件是否存在
file.createNewFile();
}
FileOutputStream fos=new FileOutputStream(topath);//指定你要写人的图片
int n=0;
byte [] b=new byte[(int)((CharSequence) fis).length()];
while ((n=fis.read(b))!=-1) {
fos.write(b,0,n);
}
fos.close();
fis.close();
}
}