Java新手 - 我正在尝试导入包含整数的.txt文件。 最后我想将整数导入到一个arraylist中,然后创建一个频率分布并计算平均值。
目前我正在努力使用文件对话框,这是我的最终目标。我可以使用显示的代码中的文件路径导入.txt。如果有人可以帮我解决如何使用对话框的问题,我们将不胜感激!
import java.io.*;
import java.util.*;
public class Distribution {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Enter a complete file path to file you would like to open:");
String fileName = input.nextLine();
File inFile = new File(fileName);
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
}
}
catch (Exception e) {
System.out.println(e);
}
finally {
try {
ins.close();
}
catch (Exception e) {
}
}
} // main end
}
答案 0 :(得分:0)
嗯,这很简单。
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
class DistributionUI {
public static void main(String[] args) {
System.out.println("Enter a complete file path to file you would like to open:");
final JFileChooser fchooser = new JFileChooser() {
private static final long serialVersionUID = 1L;
public void approveSelection() {
File inFile = getSelectedFile();
if (inFile.exists() ) {
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
ins.close();
} catch (Exception e) {
}
}
}
super.approveSelection();
}
};
fchooser.setCurrentDirectory(new File("."));
fchooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("my file", "txt");
fchooser.addChoosableFileFilter(filter);
fchooser.showOpenDialog(null);
} // main end
}