我一直收到文件或目錄不存在。我在創建Spring應用程序上下文的Groovy腳本中運行。我很容易使用相同類型的路徑在不同的文件中讀取數據。但是,我正在閱讀的文件位於Spring的類路徑中。這個腳本可能由不同文件系統的許多人運行,所以我不能硬編碼路徑。我需要一個相對路徑。將新文件保存到任何目錄Groovy
這是在課堂上面,但重要的信息。
private static String saveFilesToLocation = "/retrieve/";
這是代碼。
CSVReader reader = new CSVReader(new InputStreamReader(balanceFile), SEPARATOR)
String[] nextLine
int counter = 0;
while ((nextLine = reader.readNext()) != null) {
counter++
if (nextLine != null && (nextLine[0] != 'FileLocation')) {
counter++;
try {
//Remove 0, only if client number start with "0".
String fileLocation = nextLine[0];
byte[] fileBytes = documentFileService.getFile(fileLocation);
if (fileBytes != null) {
String fileName = fileLocation.substring(fileLocation.indexOf("/") + 1, fileLocation.length());
File file = new File(saveFilesToLocation+fileLocation);
file.withOutputStream {
it.write fileBytes
}
println "$counter) Wrote file ${fileLocation} to ${saveFilesToLocation+fileLocation}"
} else {
println "$counter) UNABLE TO RETRIEVE FILE: $fileLocation";
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
字符串中的路徑有我期望的,沒有額外的字符。
UPDATE:
感謝loteq你的回答將工作太,並擁有比我們那個工作最終的結果更好grooviness。由於它是一種一次性的,我們沒有時間去改變你有更好的版本。
下面是我們工作的代碼,除了saveFilesToLocation被設置爲現在已存在的目錄之外,它與上面的代碼完全相同。之前的那個不存在,我們需要調用mkdir,如建議的loteq 。
private static String saveFilesToLocation = "/tmp/retrieve/";
CSVReader reader = new CSVReader(new InputStreamReader(balanceFile), SEPARATOR)
String[] nextLine
int counter = 0;
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null && (nextLine[0] != 'FileLocation')) {
counter++;
try {
//Remove 0, only if client number start with "0".
String fileLocation = nextLine[0];
byte[] fileBytes = documentFileService.getFile(fileLocation);
if (fileBytes != null) {
String fileName = fileLocation.substring(fileLocation.indexOf("/") + 1, fileLocation.length());
File file = new File(saveFilesToLocation+fileName);
file.withOutputStream {
it.write fileBytes
}
println "$counter) Wrote file ${fileLocation} to ${saveFilesToLocation+fileLocation}"
} else {
println "$counter) UNABLE TO RETRIEVE FILE: $fileLocation";
}
} catch (Exception e) {
e.printStackTrace()
}
} else {
counter++;
}
}