簡體   English   中英

如何在Java中刪除帶雙引號的單引號

[英]How to remove single quotes with double quotes in java

我對正則表達式模式匹配一​​無所知,當我通過exec()命令運行批處理文件時,出現以下錯誤,即文件路徑中的單引號有問題,即

錯誤是-

Windows無法找到“ C:\\ Program”。

當CMD嘗試進入所需目錄時,單引號引起了麻煩。 所以,任何人都可以告訴我在這里做什么??

我創建了一個批處理文件來編譯和運行Java程序,我有一個名為createrunbat(String,String)的函數,以及以下代碼:

private File createrunbat(String str,String par)
 {
 if(str.startsWith("Text Editor-",0))
 {
     str=str.replaceFirst("Text Editor-","");
 }
 String sng,s2;
 File fe;
 try{

 FileOutputStream fos;
 DataOutputStream dos;

 sng=str;

 int a=sng.indexOf(".");

 sng=sng.substring(0,a);

 file=new File(jfc.getSelectedFile().getParent(),sng+".bat");

 fd=file.getAbsoluteFile();

 str=fd.getParent().substring(0, 2);

 fos=new FileOutputStream(file);
 dos=new DataOutputStream(fos);

 dos.writeBytes("@echo off \n");
 dos.writeBytes("cd\\"+"\n");

 if(fd.getParentFile().isDirectory())
 {
     dos.writeBytes(str+"\n");
 }
 s2=jfc.getSelectedFile().getParent();//I am having single quote problem from here
 dos.writeBytes("cd "+s2+"\\"+"\n");
 dos.writeBytes("javac "+sng+".java"+"\n");
 dos.writeBytes("java "+sng+" "+par+"\n");
 dos.writeBytes("pause \n");
 dos.writeBytes("exit \n");
 dos.close();
 }
 catch(FileNotFoundException ex)
 {
 }
 catch(IOException ex2)
 {
     JOptionPane.showMessageDialog(this,ex2.toString());
 }

  return fd;
 }

我認為這種情況更多的是路徑名稱中的空格引起麻煩,您將需要在路徑兩邊加上引號

dos.writeBytes ("cd \"" + s2 +"\""+"\n");

您可能將錯誤輸出與輸入混淆了。

Windows cannot find 'C:\Program'.

那里的單引號用於包裝有問題的數據,因此開發人員可以了解導致問題的輸入范圍。 單引號不屬於您的程序解釋的一部分。

正如其他人所建議的那樣,我認為真正的問題是您的路徑中的空白。 您的命令行將路徑讀取為兩個單獨的參數,而不是一個。 具有諷刺意味的是,將路徑用引號引起來應該可以解決此問題。

'C:\Program Files\SomePlace\...'
           ^ gets cut on whitespace and becomes two arguments instead of one:
'C:\Program' and 'Files\SomePlace\...'

'"C:\Program Files\SomePlace\..."'
 ^ quotes will keep the path together as a single argument

編輯:如何包裝路徑。

Java1在他們的答案中有一個很好的解決方案,因此我將提供一種使用String格式的替代方法。

String safePath = String.format("\"%s\"", jfc.getSelectedFile().getParent().getAbsolutePath()); 

在這種情況下,String.format()方法的第一個參數是要使用的模式,第二個參數是要替換的變量。
路徑周圍的實際引號必須轉義( \\" ),因為它們在java中具有特殊的含義,表示字符串的開始或結尾。您必須轉義它們才能在String中使用它們。占位符是路徑的放置位置( %s )。

邊注:

您確實應該在代碼中使用更具描述性的變量名。 使用諸如s2sngfefd類的名稱是非常糟糕的做法。 命名和描述時要保持描述性和准確性,調試和編寫代碼將變得更加容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM