java中读取文件总结
1、读文件:
readLine()是BufferedReader类的一个方法,它每次从缓冲里读一行数据。
BufferedReader类参数可为:InputStreamReader、FileReader类型
FileReader(File file)
FileReader(String fileName)
InputStreamReader(InputStream in)
//接收键盘输入作为输入流,把输入流放到缓冲流里面
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferReader in=new BufferReader(new FileReader(name))
请编写一个字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,让程序通过这个包装类读取某个文本文件(例如,一个java源文件)时,能够在读取的每行前面都加上有行号和冒号。
void doPack(String fileNameAndPath)
{
FileReader fr;
try {
fr=new FileReader(fileNameAndPath);
BufferedReader br=new BufferedReader(fr);
String readLine=null;
int lineNumber=1;
while((readLine=br.readLine())!=null)
{
readLine=lineNumber+":"+readLine;
System.out.println(readLine);
lineNumber++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
易错地方:
while(br.readLine()!=null){
System.out.println(br.readLine());
}
其中每个循环(一次打印)br.readLine()被执行了两次,当然是隔行打印!!.
应该是
BufferedReader br=new BufferedReader(file);
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}
2、写文件:
BufferWriter(Writer out)
BufferWriter的参数类型可为:FileWriter、OutputStreamWriter
FileWriter(String fileName)
FileWriter(File file)
OutputStreamWriter(OutputStream out)
1、
File file = new File(“D:\\abc.txt“);
FileWriter fw = new FileWriter("f:/jackie.txt");//创建FileWriter对象,用来写入字符流
BufferedWriter output = new BufferedWriter(fw);
output.write(s1);
2.
Writer out
= new BufferedWriter(new OutputStreamWriter(System.out));
3、
FileOutputStream fo = new FileOutputStream(filePath);
OutputStreamWriter out = new OutputStreamWriter(fo, "UTF-8");
out.write(fileContent);
out.close();
4、
// 写源文件
PrintStream print = null;
try {
print = new PrintStream(file.getPath() + "/" + proxy + ".java", "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
String code = sb.append("\n").toString();
print.print(code);
print.close();
JDK:
public PrintStream(String fileName, String csn)
throws FileNotFoundException, UnsupportedEncodingException
{
this(false, new FileOutputStream(fileName));
init(new OutputStreamWriter(this, csn));
}
private void init(OutputStreamWriter osw) {
this.charOut = osw;
this.textOut = new BufferedWriter(osw);
}
其他:
FileOutputStream 用于写入诸如图像数据之类的原始字节的流。
FileWriter只能写文本文件
InputStream in = new BufferedInputStream( new FileInputStream(filePath));
例子:
private void copy(File src, File dst) {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* Reads some number of bytes from the input stream and stores them into
* the buffer array <code>b</code>. The number of bytes actually read is
* returned as an integer.
*/
public int read(byte b[])
/*
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this output stream.
*/
public void write(byte b[], int off, int len)
。。。
InputStream转byte[]:
private byte[] InputStreamToByte(InputStream is) throws IOException {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1) {
bytestream.write(ch);
}
byte bb[] = bytestream.toByteArray();
bytestream.close();
return bb;
}
byte[] 转InputStream
byte[] data;
InputStream is = new ByteArrayInputStream(data);
二、Java中properties文件的读写
1.总结:
setProperty()中,如果你的属性是文件里面没有的属性,系统会进行追加,如果你的属性,在系统中已经存在,那么系统就会进行更新操作.
读取1:
// 根据key读取value
public void readValue(String filePath, String key) {
Properties props = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
//Thread.currentThread().getContextClassLoader().getResourceAsStream("eop.properties");
props.load(in); // 从输入流中读取属性列表(键和元素对)
String value = props.getProperty(key);
}
// 读取properties的全部信息
public static void readProperties(String filePath) {
Properties props = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
props.load(in);
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = props.getProperty(key);
}
}
读取2、
ResourceBundle bundle = ResourceBundle.getBundle("currencyURL");
Enumeration<String> enums = bundle.getKeys();
while (enums.hasMoreElements()) {
String key = enums.nextElement();
String value = bundle.getString(key);
}
currencyURL.properties:
写入:
InputStream fis = new FileInputStream(filePath);
prop.load(fis);
prop.setProperty(parameterName, parameterValue);
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
prop.store( new FileOutputStream(filePath), "commont");
//void java.util.Properties.store(OutputStream out, String comments)
3、将文件转换为字节流byte[]
法1:
String fileName = "d:/gril.gif"; //源文件
String strBase64 = null;
try {
InputStream in = new FileInputStream(fileName);
// in.available()返回文件的字节长度
byte[] bytes = new byte[in.available()];
// 将文件中的内容读入到数组中
in.read(bytes);
in.close();
法2:
InputStream in = new FileInputStream(filename);
ByteArrayOutputStream ba = new ByteArrayOutputStream();
int i = -1;
while( (i = in.read()) != -1 ){
ba.write(i);
}
byte[] bb = ba.toByteArray();
//想要直接弹出,需加上response这4句
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
response.setContentLength(bb.length);
try {
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(bb, 0, bb.length);
ouputStream.flush();
ouputStream.close();
} catch (IOException e) {
e.printStackTrace();
throw new SystemException(e.getMessage());
}
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try
{
bufferedInputStream = new BufferedInputStream(new FileInputStream(tmpFile));
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + getDownloadFileName(tmpFile.getName()) + "\"");
bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
byte[] cbuf = new byte[1024];
int count;
while ((count = bufferedInputStream.read(cbuf, 0, 1024)) != -1)
{
bufferedOutputStream.write(cbuf, 0, count);
bufferedOutputStream.flush();
}
}
catch (Exception e)
{
log.error("用户点击取消下载", e);
return;
}
finally
{
try
{
if (bufferedOutputStream != null)
{
bufferedOutputStream.close();
}
}
catch (Exception e) {
log.error("bufferedOutputStream.close()", e);
}
try
{
assert (bufferedInputStream != null);
bufferedInputStream.close();
}
catch (Exception e) {
log.error("bufferedInputStream.close()", e);
}
}
java中字节流与字符流的主要区别
流就是stream,是程序输入或输出的一个连续的字节序列,设备(例如鼠标,键盘,磁盘,屏幕和打印机)的输入和输出都是用流来处理的。在C语言中,所有的流均以文件的形式出现---不一定是物理磁盘文件,还可以是对应与某个输入/输出源的逻辑文件
字节流继承于InputStream OutputStream,字符流继承于InputStreamReader OutputStreamWriter。在java.io包中还有许多其他的流,主要是为了提高性能和使用方便。
字节流是最基本的,所有的InputStream和OutputStream的子类都是字节流,其主要用于处理二进制数据,并按字节来处理。实际开发中很多的数据是文本,这就提出了字符流的概念。它按虚拟机的encode来处理,也就是要进行字符流的转化。这两者之间通过InputStreamReader和OutputStreamWriter来关联。实际上通过byte[]和String来关联在实际开发中出现的汉字问题,这都是在字符流和字节流之间转化不统一造成的。
字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串,而字节流处理单元为1个字节, 操作字节和字节数组。所以字符流是由Java虚拟机将字节转化为2个字节的Unicode字符为单位的字符而成的,所以它对多国语言支持性比较好!如果是 音频文件、图片、歌曲,就用字节流好点,如果是关系到中文(文本)的,用字符流好点.
所有文件的储存是都是字节(byte)的储存,在磁盘上保留的并不是文件的字符而是先把字符编码成字节,再储存这些字节到磁盘 。在读取文件(特别是文本文件)时,也是一个字节一个字节地读取以形成字节序列.
字节流可用于任何类型的对象,包括二进制对象,而字符流只能处理字符或者字符串 ; 2. 字节流提供了处理任何类型的IO操作的功能,但它不能直接处理Unicode字符,而字符流就可以。
字节流转化为字符流,实际上就是byte[]转化为String。
字符流转化为字节流,实际上就是String转化为byte[]。
至于java.io中还出现了许多其他的流,主要是为了提高性能和使用方便,如BufferedInputStream、PipedInputStream等。
===============================================================================
一.获得控制台用户输入的信息
public String getInputMessage() throws IOException...{
System.out.println("请输入您的命令∶");
byte buffer[]=new byte[1024];
int count=System.in.read(buffer);
char[] ch=new char[count-2];//最后两位为结束符,删去不要
for(int i=0;i<count-2;i++)
ch[i]=(char)buffer[i];
String str=new String(ch);
return str;
}
可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。
二.复制文件
1.以文件流的方式复制文件
public void copyFile(String src,String dest) throws IOException...{
FileInputStream in=new FileInputStream(src);
File file=new File(dest);
if(!file.exists())
file.createNewFile();
FileOutputStream out=new FileOutputStream(file);
int c;
byte buffer[]=new byte[1024];
while((c=in.read(buffer))!=-1)...{
for(int i=0;i<c;i++)
out.write(buffer[i]);
}
in.close();
out.close();
}
该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式
三.写文件
1.利用PrintStream写文件
public void PrintStreamDemo()...{
try ...{
FileOutputStream out=new FileOutputStream("D:/test.txt");
PrintStream p=new PrintStream(out);
for(int i=0;i<10;i++)
p.println("This is "+i+" line");
} catch (FileNotFoundException e) ...{
e.printStackTrace();
}
}
2.利用StringBuffer写文件
public void StringBufferDemo() throws IOException......{
File file=new File("/root/sms.log");
if(!file.exists())
file.createNewFile();
FileOutputStream out=new FileOutputStream(file,true);
for(int i=0;i<10000;i++)......{
StringBuffer sb=new StringBuffer();
sb.append("这是第"+i+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 ");
out.write(sb.toString().getBytes("utf-8"));
}
out.close();
}
该方法可以设定使用何种编码,有效解决中文问题。
四.文件重命名
public void renameFile(String path,String oldname,String newname)...{
if(!oldname.equals(newname))...{//新的文件名和以前文件名不同时,才有必要进行重命名
File oldfile=new File(path+"/"+oldname);
File newfile=new File(path+"/"+newname);
if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
System.out.println(newname+"已经存在!");
else...{
oldfile.renameTo(newfile);
}
}
}
五.转移文件目录
转移文件目录不等同于复制文件,复制文件是复制后两个目录都存在该文件,而转移文件目录则是转移后,只有新目录中存在该文件。
public void changeDirectory(String filename,String oldpath,String newpath,boolean cover)...{
if(!oldpath.equals(newpath))...{
File oldfile=new File(oldpath+"/"+filename);
File newfile=new File(newpath+"/"+filename);
if(newfile.exists())...{//若在待转移目录下,已经存在待转移文件
if(cover)//覆盖
oldfile.renameTo(newfile);
else
System.out.println("在新目录下已经存在:"+filename);
}
else...{
oldfile.renameTo(newfile);
}
}
}
六.读文件
1.利用FileInputStream读取文件
public String FileInputStreamDemo(String path) throws IOException...{
File file=new File(path);
if(!file.exists()||file.isDirectory())
throw new FileNotFoundException();
FileInputStream fis=new FileInputStream(file);
byte[] buf = new byte[1024];
StringBuffer sb=new StringBuffer();
while((fis.read(buf))!=-1)...{
sb.append(new String(buf));
buf=new byte[1024];//重新生成,避免和上次读取的数据重复
}
return sb.toString();
}
2.利用BufferedReader读取
在IO操作,利用BufferedReader和BufferedWriter效率会更高一点
public String BufferedReaderDemo(String path) throws IOException...{
File file=new File(path);
if(!file.exists()||file.isDirectory())
throw new FileNotFoundException();
BufferedReader br=new BufferedReader(new FileReader(file));
String temp=null;
StringBuffer sb=new StringBuffer();
temp=br.readLine();
while(temp!=null)...{
sb.append(temp+" ");
temp=br.readLine();
}
return sb.toString();
}
3.利用dom4j读取xml文件
public Document readXml(String path) throws DocumentException, IOException...{
File file=new File(path);
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
SAXReader saxreader = new SAXReader();
Document document = (Document)saxreader.read(bufferedreader);
bufferedreader.close();
return document;
}
七.创建文件(文件夹)
1.创建文件夹
public void createDir(String path)...{
File dir=new File(path);
if(!dir.exists())
dir.mkdir();
}
2.创建新文件
public void createFile(String path,String filename) throws IOException...{
File file=new File(path+"/"+filename);
if(!file.exists())
file.createNewFile();
}
八.删除文件(目录)
1.删除文件
public void delFile(String path,String filename)...{
File file=new File(path+"/"+filename);
if(file.exists()&&file.isFile())
file.delete();
}
2.删除目录
要利用File类的delete()方法删除目录时,必须保证该目录下没有文件或者子目录,否则删除失败,因此在实际应用中,我们要删除目录,必须利用递归删除该目录下的所有子目录和文件,然后再删除该目录。
public void delDir(String path)...{
File dir=new File(path);
if(dir.exists())...{
File[] tmp=dir.listFiles();
for(int i=0;i<tmp.length;i++)...{
if(tmp[i].isDirectory())...{
delDir(path+"/"+tmp[i].getName());
}
else...{
tmp[i].delete();
}
}
dir.delete();
}
}