Java—FileOperator

Swing中JFileChooser的用法

showSaveDialog:

JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));  //设置初始路径
int result = jfc.showSaveDialog(this);
if (result != JFileChooser.APPROVE_OPTION)
    return;
        
//附上这段,描述两种判断输入为空的方法
if (this.jtaContent.getText().trim().length() == 0)  //if (this.jtaContent.getText().trim().equals(""))
{
    JOptionPane.showMessageDialog(new JFrame(), "请输入内容");
    return;
}

showOpenDialog:

JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
int result = jfc.showOpenDialog(this);
if (result != JFileChooser.APPROVE_OPTION)
    return;
File file = jfc.getSelectedFile();
this.jtfFilePath.setText(file.getAbsolutePath());

读写文本文件——面向字符(16位的Unicode)的流Writer、Reader:

和C#一样,当文件不存在时,java的Writer会新建一个文件,Reader则会抛出异常。

FileWriter、BufferedWriter的使用:

File file = jfc.getSelectedFile();    //JFileChooser
try
{
    FileWriter fileWriter = new FileWriter(file);
    BufferedWriter writer = new BufferedWriter(fileWriter);
    writer.write(this.jtaContent.getText().replace("\n", "\r\n"));
    writer.close();
    fileWriter.close();
}
catch (Exception e)
{
    e.printStackTrace();
}

FileReader、BufferedReader:

File file = jfc.getSelectedFile();
this.jtfFilePath.setText(file.getAbsolutePath());
try
{
    FileReader fileReader = new FileReader(file);
    BufferedReader reader = new BufferedReader(fileReader);
    String content = "";
    while ((content = reader.readLine()) != null) //先赋值,后判断content的值
    {
        this.jtaContent.append(content + "\n");
        sum += Integer.parseInt(content);
    }
    reader.close();
    fileReader.close();
}
catch (Exception e)
{
    e.printStackTrace();
}

用字节流FileInputStream、FileOutputStream来读写文本:

FileInputStream fiStream = new FileInputStream("F:/wukong.txt");
byte[] arr = new byte[1024];
int size = fiStream.read(arr, 0, arr.length);
            
FileOutputStream foStream = new FileOutputStream("F:/shutao.txt");
foStream.write(arr, 0, size);
            
foStream.close();
fiStream.close();

读写二进制文件——面向字节的流InputStream、OutputStream:

DataOutputStream结合FileOutputStream使用:

FileOutputStream foStream = new FileOutputStream("F:/shutao.dat");
DataOutputStream dataStream = new DataOutputStream(foStream);
dataStream.write(255);
foStream.close();
dataStream.close();

DataInputStream结合FileInputStream使用:

FileInputStream fiStream = new FileInputStream("F:/shutao.dat");
DataInputStream dataStream = new DataInputStream(fiStream);
System.out.println(dataStream.read());
fiStream.close();
dataStream.close();

File类

File类只能获取文件、目录的属性,不能创建文件、目录。

常用的属性有:

posted @ 2017-01-11 12:58  不抛弃,不放弃  阅读(1496)  评论(0编辑  收藏  举报