什么是java中的“file”数据类型..?

时间:2013-02-11 08:16:58

标签: java file

import java.io.*;

class SplitFile    
{    
    private File fSplit;
    private int sizeInBytes;

    private int count;

    public static void main(String[] args) throws IOException
    {    
        Console con = System.console();

        String fileName;

        int size = 0;

        System.out.print("Enter the file name to split: ");

        fileName = con.readLine();

        System.out.print("Enter the size of the target file: ");

        size = Integer.parseInt(con.readLine());

        SplitFile sf = new SplitFile(fileName, size);

        sf.split();

    }

    public File checkFileExists(String fName)    
    {    
        File f = new File(fName);

        if (!f.exists())    
        {    
            System.out.println("File " + fName + " does not exists");

            System.exit(0);

        }

        return f;

    }

    public int validateSize(int s)    
    {    
        if (fSplit.length() < s)    
        {

            System.out.println("Invalid Size");

            System.exit(0);

        }

        return s;

    }

    public String createNextFileName()    
    {    
        ++count;

        String fileName;

        fileName = "part_" + count + "." + fSplit.getName();

        return fileName;

    }

    public SplitFile(String fName, int s)    
    {

        fSplit = checkFileExists(fName);

        sizeInBytes = validateSize(s);

        count = 0;

    }

    public void split() throws IOException

    {

        FileInputStream fis = new FileInputStream(fSplit);

        BufferedInputStream bis = new BufferedInputStream(fis);

        File fileSegment = new File(createNextFileName());

        FileOutputStream fos = new FileOutputStream(fileSegment);

        BufferedOutputStream bos = new BufferedOutputStream(fos);

        int ch;

        int currentByteCount = 0;

        while ((ch = bis.read()) != -1)

        {

            bos.write(ch);

            ++currentByteCount;

            if (currentByteCount == sizeInBytes)

            {

                bos.close();

                fos.close();

                fileSegment = new File(createNextFileName());

                fos = new FileOutputStream(fileSegment);

                bos = new BufferedOutputStream(fos);

                currentByteCount = 0;

            }

        }

        bis.close();

        fis.close();

        bos.close();

        fos.close();

    }

}

2 个答案:

答案 0 :(得分:4)

基于文档

  

文件和目录路径名的抽象表示。

File是参考类型。它用于处理文件(例如创建)通过查看link

来理解它会更容易

<强>更新

通过查看您之前回答的评论,我发现您不了解/不熟悉java中的不同数据类型,有两种数据类型。

  1. 原始数据类型(char,int,boolean)
  2. 参考类型/对象(用户     定义的类,超类Object,在你的情况下,     File

答案 1 :(得分:2)

文件 对象 就是一个用于处理文件的对象,您可以在文档中阅读here