# 使用 JNLP API 访问客户端

> 原文： [https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/usingJNLPAPI.html](https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/usingJNLPAPI.html)

使用 Java 网络启动协议（JNLP）启动时，富 Internet 应用程序（RIA）可以在用户的​​许可下访问客户端。考虑文本编辑器 applet 示例，以了解如何使用基于 JNLP API 的服务。文本编辑器有一个文本区域和标记为“打开”，“保存”和“另存为”的按钮。文本编辑器可用于打开现有文本文件，对其进行编辑，然后将其保存回磁盘。

接下来显示文本编辑器小程序。

<noscript>A browser with JavaScript enabled is required for this page to operate properly.</noscript>

* * *

**Note:**  If you don't see the applet running, you need to install at least the [Java SE Development Kit (JDK) 6 update 10](http://www.oracle.com/technetwork/java/javase/downloads/index.html) release.

* * *

* * *

**Note:**  If you don't see the example running, you might need to enable the JavaScript interpreter in your browser so that the Deployment Toolkit script can function properly.

* * *

[`TextEditor`](examples/applet_JNLP_API/src/TextEditor.java) 和 [`TextEditorApplet`](examples/applet_JNLP_API/src/TextEditor.java) 类布局用户界面并将其显示为小程序。 [`FileHandler`](examples/applet_JNLP_API/src/FileHandler.java) 类包含有关使用基于 JNLP API 的服务的核心功能。

请记住，本主题中描述的技术也适用于 Java Web Start 应用程序。

要使用 JNLP 服务，请首先检索对服务的引用。 `FileHandler`类的`initialize`方法检索对 JNLP 服务的引用，如以下代码片段所示：

```
private static synchronized void initialize() {
    ...
    try {
        fos = (FileOpenService)
            ServiceManager.lookup("javax.jnlp.FileOpenService");
        fss = (FileSaveService)
            ServiceManager.lookup("javax.jnlp.FileSaveService");
    } catch (UnavailableServiceException e) {
        ...
    }
}

```

在引用所需服务之后，调用服务上的方法以执行必要的操作。 `FileHandler`类的`open`方法调用 [`FileOpenService`](https://docs.oracle.com/javase/8/docs/jre/api/javaws/jnlp/javax/jnlp/FileOpenService.html) 类的`openFileDialog`方法来显示文件选择器。 `open`方法返回所选文件的内容。

```
public static String open() {
    initialize();
    try {
        fc = fos.openFileDialog(null, null);
        return readFromFile(fc);
    } catch (IOException ioe) {
        ioe.printStackTrace(System.out);
        return null;
    }
}

```

类似地，`FileHandler`类的`save`和`saveAs`方法调用 [`FileSaveService`](https://docs.oracle.com/javase/8/docs/jre/api/javaws/jnlp/javax/jnlp/FileSaveService.html) 类的相应方法，以使用户能够选择文件名并将文本区域的内容保存到磁盘。

```
public static void saveAs(String txt) {
    initialize();
    try {
        if (fc == null) {
            // If not already saved.
            // Save-as is like save
            save(txt);
        } else {
            fc = fss.saveAsFileDialog(null, null,
                                         fc);
            save(txt);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace(System.out);
    }
}

```

在运行时，当 RIA 尝试打开或保存文件时，用户会看到一个安全对话框，询问他们是否要允许该操作。仅当用户允许 RIA 访问其环境时，操作才会继续。

接下来显示 [`FileHandler`](examples/applet_JNLP_API/src/FileHandler.java) 类的完整来源。

```
// add javaws.jar to the classpath during compilation 
import javax.jnlp.FileOpenService;
import javax.jnlp.FileSaveService;
import javax.jnlp.FileContents;
import javax.jnlp.ServiceManager;
import javax.jnlp.UnavailableServiceException;
import java.io.*;

public class FileHandler {

    static private FileOpenService fos = null;
    static private FileSaveService fss = null;
    static private FileContents fc = null;

    // retrieves a reference to the JNLP services
    private static synchronized void initialize() {
        if (fss != null) {
            return;
        }
        try {
            fos = (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService");
            fss = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
        } catch (UnavailableServiceException e) {
            fos = null;
            fss = null;
        }
    }

    // displays open file dialog and reads selected file using FileOpenService
    public static String open() {
        initialize();
        try {
            fc = fos.openFileDialog(null, null);
            return readFromFile(fc);
        } catch (IOException ioe) {
            ioe.printStackTrace(System.out);
            return null;
        }
    }

    // displays saveFileDialog and saves file using FileSaveService
    public static void save(String txt) {
        initialize();
        try {
            // Show save dialog if no name is already given
            if (fc == null) {
                fc = fss.saveFileDialog(null, null,
                        new ByteArrayInputStream(txt.getBytes()), null);
                // file saved, done
                return;
            }
            // use this only when filename is known
            if (fc != null) {
                writeToFile(txt, fc);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace(System.out);
        }
    }

    // displays saveAsFileDialog and saves file using FileSaveService
    public static void saveAs(String txt) {
        initialize();
        try {
            if (fc == null) {
                // If not already saved. Save-as is like save
                save(txt);
            } else {
                fc = fss.saveAsFileDialog(null, null, fc);
                save(txt);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace(System.out);
        }
    }

    private static void writeToFile(String txt, FileContents fc) throws IOException {
        int sizeNeeded = txt.length() * 2;
        if (sizeNeeded > fc.getMaxLength()) {
            fc.setMaxLength(sizeNeeded);
        }
        BufferedWriter os = new BufferedWriter(new OutputStreamWriter(fc.getOutputStream(true)));
        os.write(txt);
        os.close();
    }

    private static String readFromFile(FileContents fc) throws IOException {
        if (fc == null) {
            return null;
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(fc.getInputStream()));
        StringBuffer sb = new StringBuffer((int) fc.getLength());
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        br.close();
        return sb.toString();
    }
}

```

* * *

**Note:** To compile Java code that has a reference to classes in the `javax.jnlp` package, include `<your JDK path>/jre/lib/javaws.jar` in your classpath. At runtime, the Java Runtime Environment software automatically makes these classes available to RIAs.

* * *

[下载 _ 文本编辑器小程序 _ 示例的源代码](examplesIndex.html#AppletJNLPAPI)以进一步试验。