简体   繁体   中英

Importing files from local file system in Java

Does Java allow you to import files from a local directory into a program without specifying an actual file? I want the user to choose their own text file to import into my program. I've searched only to find examples on how to read in files with the .txt file already known.

There are multiple ways in which you can allow a user to select a file without actually hard-coding the filename into the program.

Here is one example using the Swing class of JFileChooser

import javax.swing.JFileChooser;
import java.io.File;

public class ChooseFile 
{

    public static void main(String[] args) 
    {
        // Create JFileChooser
        JFileChooser fileChooser = new JFileChooser();

        // Set the directory where the JFileChooser will open to
        // Uncomment one of these below as an example
        // fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        // fileChooser.setCurrentDirectory(new File("c:\\"));

        // Show the file select box to the user
        int result = fileChooser.showOpenDialog(null);   

        // Did the user select the "Open" button
        if(result == JFileChooser.APPROVE_OPTION)        
            System.out.println("File chosen: " + fileChooser.getSelectedFile());        
        else
            System.out.println("No file chosen");          
    } 
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM