Java文件操作

1.以文件流的方式复制文件

将一个已存在文件复制到指定位置,如本例中将源文件"/home/hadoop/Scene1"拷贝一份重命名为“/home/hadoop/Scene1bak”

代码如下:

View Code
package erp.sjtu.xw;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
    public static void main(String args[]) throws IOException
    {
        CopyFile cf=new CopyFile();
        String src="/home/hadoop/Scene1";
        String dest="/home/hadoop/Scene1bak";
        cf.copyFile(src, dest);
    }
    
    /**以文件流的方式复制文件
     * @param src 文件源目录
     * @param dest 文件目的目录
     * @throws IOException 
     * 该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式
     */
    
    public void copyFile(String src,String dest) throws IOException
    {
        FileInputStream in=new FileInputStream(src);//定义输入流
        File file=new File(dest);//定义文件,指定位置"dest"可能已经存在了该文件,如果不存在需要创建。
        if(!file.exists())//如果文件不存在,则调用创建文件的方法
            file.createNewFile();
        FileOutputStream out=new FileOutputStream(file);//定义输出流
        int c;
        byte buffer[]=new byte[1024];//定义缓冲大小。
        /**
         * 将输入文件中的文本内容读入缓冲buffer中去。
         * 如果文本大小小于buffer的容量,那么读一次就可以。
         * 如果大于buffer大小,则需要多次读取。 
         */
        while((c=in.read(buffer))!=-1)//从输入流中读取文本内容读入buffer,知道读完为止
        {                                                        
            System.out.println(c);//输出buffer中读取的文本长度
            for(int i=0;i<c;i++)
                out.write(buffer[i]);//将buffer中的内容吸入输出流。
        }
        in.close();
        out.close();
    }
}

输出结果为:

1024

89

而Scene1文件大小也刚好为(1113=1024+89)字节

2.获得控制台用户输入的信息

这个程序用户获得控制台输入的信息,代码如下:

View Code
package erp.sjtu.xw;
import java.io.IOException;
public class GetConsoleInputMessage {
    public static void main(String args[]) throws IOException
    {
        GetConsoleInputMessage instance=new GetConsoleInputMessage();
        String str=instance.getInputMessage();
        System.out.println(str);
        System.exit(0);    
    }
    /**获得控制台用户输入的信息
     * @return
     * @throws IOException
     * 可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。
     */
    public  String getInputMessage() throws IOException{
        String str=null;
        System.out.println("请输入命令:");
        byte buffer[]=new byte[1024];//创建缓冲
        int count=System.in.read(buffer);//将console中的输入写入到缓冲buffer中,并返回缓冲字符串长度。
        System.out.println(count);
        //char ch[]=new char[count-2];//buffer中最后两位是结束符,没有意思,因此删除。
        char ch[]=new char[count-1];//定义一个字符数组,长度为count-1,因为buffer中最后一位是结束符,没有意思,因此删除。
        for(int i=0;i<count-1;i++)
        {
            ch[i]=(char)buffer[i];
//            str=new String(ch);
//            System.out.println(str);
        }
        str=new String(ch);//将字符数组转变成字符串。
        return str;
    }
}

输出结果:

请输入命令:
please input you commond
25
please input you commond

 注意:这里输入输出的buffer长度是25,但是实际上字符串中有用的只有24个字符,这是因为buffer中最后一位是结束符。

3.利用PrintStream写文件

使用PrintStream能够往空文件中写入文本,代码如下:

View Code
package erp.sjtu.xw;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class PrintStreamDemo {
    public static void main(String args[]) throws IOException
    {
        PrintStreamDemo psd=new PrintStreamDemo();
        psd.printStreamDemo();//test printStreamDemo()
        psd.printStreamDemo2();////test printStreamDemo2()
    }
    
    public void printStreamDemo() throws IOException
    {
        try{
            String src="/home/hadoop/printStreamDemo";//源文件路径
            File file=new File(src);//定义文件,如果不存在路径所指定的文件则创建
            if(!file.exists())
                file.createNewFile();
            FileOutputStream out=new FileOutputStream(file);//定义文件输出流
            PrintStream ps=new PrintStream(out);//往文件输出流中打印内容
            for(int i=0;i<10;i++)
                ps.println("This is "+i+" line.");
            
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }
    }
    /**
     * 利用PrintStream写文件
     */
    public void printStreamDemo2() throws IOException
    {
        try{
            /**
             * 注:FileOutputStream out=new FileOutputStream("/home/hadoop/printStreamDemo2");
             * 如果本地目录有文件printStreamDemo3,则文本写入该文件中。
             * 如果本地目录中没有printStreamDemo3这个文件,会自动创建该文件,并向其中写入文本。
             * 这是前面如下代码的操作集合
             * String src="/home/hadoop/printStreamDemo";//源文件路径
             * File file=new File(src);//定义文件,如果不存在路径所指定的文件则创建
             * if(!file.exists())
             *         file.createNewFile();
             * FileOutputStream out=new FileOutputStream(file);//定义文件输出流
             */
            FileOutputStream out=new FileOutputStream("/home/hadoop/printStreamDemo2");
            PrintStream ps=new PrintStream(out);
            for(int i=0;i<10;i++)
                ps.println("This is "+i+" line.");
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }
    }
}

运行上述代码,将自动生成printStreamDemo和printStreamDemo2这两个文件,这了这两个文件的文本内容都是:

This is 0 line.
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
This is 5 line.
This is 6 line.
This is 7 line.
This is 8 line.
This is 9 line.

4. 利用StringBuffer写文件

代码如下:

View Code
package erp.sjtu.xw;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class StringBufferDemo {
    public static void main(String args[]) throws IOException
    {
        StringBufferDemo sbd=new StringBufferDemo();//创建对象实例
        sbd.stringBufferDemo();//调用方法,方法和类同名,有点别扭
    
    }
    /**
     * 利用StringBuffer写文件
     * 该方法可以设定使用何种编码,有效解决中文问题。
     * @throws IOException
     */
    
    public void stringBufferDemo() throws IOException
    {
        String src="/home/hadoop/StringBufferDemo";
        File file=new File(src);
        if(file.exists())
            file.createNewFile();
        FileOutputStream out=new FileOutputStream(file,true);
        for(int i=0;i<10;i++)
        {
            StringBuffer sb=new StringBuffer();
            sb.append("这是第"+i+"行。/n");//如果不加"/n"则不能实现换行。
            out.write(sb.toString().getBytes("utf-8"));
        }
        out.close();
    }
}

运行上述代码将自动生成文件StringBufferDemo,其文本内容为:

这是第0行。
这是第1行。
这是第2行。
这是第3行。
这是第4行。
这是第5行。
这是第6行。
这是第7行。
这是第8行。
这是第9行。

PS:java 流(Stream)的概念(2011-10-13)

流是 Java 中最重要的基本概念之一。文件读写、网络收发、进程通信,几乎所有需要输入输出的地方,都要用到流。流是做什么用的呢?就是做输入输出用的。为什么输入输出要用“流”这种方式呢?因为程序输入输出的基本单位是字节,输入就是获取一串字节,输出就是发送一串字节。但是很多情况下,程序不可能接收所有的字节之后再进行处理,而是接收一点处理一点。比方你下载魔兽世界,不可能全部下载到内存里再保存到硬盘上,而是下载一点就保存一点。这时,流这种方式就非常适合。在 Java 中,每个流都是一个对象。流分为两种:输入流(InputStream)和输出流(OutputStream)。对于输入流,你只要从流当中不停地把字节取出来就是了;而对于输出流,你只要把准备好的字节串传给它就行。
                               ________Java 程序                          
                               |                                                             |
           外部系统 --|--(输入流)--> 处理逻辑 --(输出流)---|--> 外部系统
                               |__________________________|
 总体而言,我们要站在内存的角度想象java的输入流与输出流。输入流就是“我们是内存,外部系统有内容要输入到内存中,所以叫输入流”。输出流就是“我们是内存,我们要将数据从内存输出,写入到外部系统,所以叫输出流。”

作者:xwdreamer
欢迎任何形式的转载,但请务必注明出处。
分享到:
原文地址:https://www.cnblogs.com/xwdreamer/p/2297029.html