Java File Operations

Source: Internet
Author: User

Java File Operations
Open a file

First, instantiate JFileChoosers. You can use FileNameExtensionFilter to set the filter. The return value of the showOpenDialog method is of the int type. Therefore, define a value. Finally, if the value is equal to JFileChooser. APPROVE_OPTION can be used to operate the file. The file path is printed here.

private JFileChooser chooser;FileNameExtensionFilter filter = new FileNameExtensionFilter(Allowed File, txt,jar);chooser.setFileFilter(filter);int value = chooser.showOpenDialog(TestOpen.this);if (value == JFileChooser.APPROVE_OPTION) {    File file = chooser.getSelectedFile();    System.out.println(file.getAbsolutePath());}

What should I do if I want to open multiple files?

chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);chooser.setMultiSelectionEnabled(true);int value = chooser.showOpenDialog(TestOpen.this);if (value == JFileChooser.APPROVE_OPTION) {    File file[] = chooser.getSelectedFiles();    for (int i = 0; i < file.length; i++) {        System.out.println(file[i].getAbsolutePath());    }}
Save files

To save the file, remember to check for exceptions. An error occurs if you accidentally save the file. Actually, it's nothing more than calling the createNewFile method.

try {    JFileChooser chooser = new JFileChooser();    int value = chooser.showSaveDialog(TestSave.this);    if (value == JFileChooser.APPROVE_OPTION) {        File newfFile = chooser.getSelectedFile();        if (newfFile.exists() == false) {            newfFile.createNewFile();        }    }} catch (HeadlessException e1) {    e1.printStackTrace();} catch (IOException e1) {    e1.printStackTrace();}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.