非法逃脱字符后跟空格 [英] llegal escape character followed by a space
问题描述
我正在编写一些代码来使用在终端中加载和运行文件的进程来运行shell脚本。我遇到的问题是由于空格而使终端识别文件名,例如:
I'm writing a bit of code to run a shell script using process that loads and runs a file in terminal. The problem I'm having is getting the filename to be recognised by terminal due to the spaces, for example :
"$ ./run_file.sh foo bar.ss"
应该在终端中运行
"$ ./run_file.sh foo\ bar.ss"
继承代码改变它取代它:
Heres the code to change it replace it:
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但是得到了
I have been tried using String.replaceAll but get
java:66: illegal escape character
i意识到我可以使用File.separatorChar:
i realise that I can use File.separatorChar :
string = string.replaceAll(" ", Character.toString(File.separatorChar)+" ");
但这似乎没有取代任何东西......
任何帮助都会很多赞赏。
but this doesn't seem to replace anything... Any help would be much appreciated.
谢谢
推荐答案
如果你想把<字符串中的code> \ 字符(转义字符),你需要转义它:
If you want to put the \
character (which is the escape character) inside a string, you'll need to escape it:
string = string.replaceAll (" ", "\\ ");
单个 \
是一个转义序列前导字符,例如 \ n
(换行符)或 \ r
(回车)。单字符转义的完整列表是:
A single \
is a escape sequence leading character, such as with \n
(newline) or \r
(carriage return). The full list of single-character escapes is:
\b backspace
\t tab
\n linefeed (newline)
\f form feed
\r carriage return
\" double quote
\' single quote
\\ backslash
这是八进制转义序列的补充,例如 \\ \\ 0
, \\\
或 \ 377
。
This is in addition to the octal escape sequences s such as \0
, \12
or \377
.
你的 separatorChar
解决方案不起作用的原因是因为它为你提供了分隔符 char(<$在UNIX及其兄弟下c $ c> / ,而不是您需要的转义字符 \
。
The reason why your separatorChar
solution won't work is because that gives you the separator char (/
under UNIX and its brethren), not the escape character \
that you need.
这篇关于非法逃脱字符后跟空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!