gpt4 book ai didi

java - 从 Java 程序中打开任何文件

转载 作者:搜寻专家 更新时间:2023-10-31 20:01:58 24 4
gpt4 key购买 nike

在 Java 中打开文件似乎有点棘手——对于 .txt 文件,必须将 File 对象与 Scanner 或 BufferedReader 对象结合使用——对于图像 IO,必须使用 ImageIcon 类——如果要从字面上从 java 打开一个 .txt 文档(类似于双击应用程序),这段代码似乎有效:

import java.io.*;

public class LiterallyOpenFile {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("notepad Text.txt");
}
}

我不是肯定的,但我认为其他文件类型/名称可以在 exec 之后的括号中替换——无论如何,我计划在用户单击要打开的文件时在 JFileChooser 中打开某些文件(当用户点击一个文件,可以使用 getSelectedFile() 方法获取该文件的路径)。尽管我更具体地希望能够从 java 程序在 Arduino IDE 中打开 Arduino 文件,例如模拟双击……也许是这样的?

import java.io.*;

public class LiterallyOpenFile {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("Arduino C:\\Arduino\\fibonacci_light\\fibonacci_light.ino");
}
}

在正确方向上的观点将不胜感激。

最佳答案

你试过吗?如果在 Windows 中有针对您的文件的注册程序,这应该可以工作。 (即默认应用程序应打开文件)

Desktop desktop = Desktop.getDesktop();
desktop.open(file);

文件参数是一个File对象。

Link to API

Link to use cases and implementation example of the Desktop class

关于java - 从 Java 程序中打开任何文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27476838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com