我正在编写一些代码来使用在终端中加载和运行文件的进程来运行 shell 脚本。我遇到的问题是由于空格而导致终端识别文件名,例如:
"$ ./run_file.sh foo bar.ss"
应该在终端中运行
"$ ./run_file.sh foo\ bar.ss"
这是更改它的代码,替换它:
JPanel panel1 = new JPanel();
JButton button = new JButton("Run");
button.setAlignmentX( Component.CENTER_ALIGNMENT);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
run();
}
});
//button.setAlignmentX(0.5);
panel1.add(button);
panel1.add(Box.createVerticalGlue());
panel1.add(button);
menuB = new JMenuBar();
JMenu dropD = new JMenu("File");
menuB.add(dropD);
JMenuItem loadR = new JMenuItem("Load file");
JMenuItem quit = new JMenuItem("Quit");
dropD.add(loadR);
dropD.add(quit);
loadR.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
JFileChooser fileopen = new JFileChooser();
int r= fileopen.showDialog(panel, "Load file");
if (r == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
String string = file.toString();
string = string.replaceAll(" ", "\ ");
//String output = aa.replaceAll("/",Character.toString(File.separatorChar));
System.out.println(string);
loadFile = file;
}
}
});
我尝试过使用 String.replaceAll 但得到
java:66: illegal escape character
我意识到我可以使用 File.separatorChar :
string = string.replaceAll(" ", Character.toString(File.separatorChar)+" ");
但这似乎并不能取代任何东西......
任何帮助将非常感激。
Thanks