[英]How can I convert a xml file to a xml written with javascript file with java?
我有來自兩個不同數據庫的兩個 XML 文件,但它們有相同的信息。 其中一個有 VSReports,另一個有 Jasperreports(JavaScript)。 我必須將 XML 文件從 VSReports 轉換為 Jasperreports。 我被允許使用的唯一編程語言是 java。
當我嘗試使用我的代碼讀取 xml 文件時,我已經陷入困境。
import javax.swing.*;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class InputBox {
public static void main(String[] args) {
Pfad();
}
//opens JFileChooser
public static void Pfad() {
JFileChooser chooser = new JFileChooser();
int rueckgabeWert = chooser.showOpenDialog(null);
if (rueckgabeWert == JFileChooser.APPROVE_OPTION) {
System.out.println("Die zu öffnende Datei ist: "
+ chooser.getSelectedFile().getName());
}
Path path = Paths.get(chooser.getSelectedFile().getName());
String content = null;
try {
content = Files.readString(path, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println the content of the file
System.out.println(content);
}
}
它適用於 txt 文件,但當我嘗試使用 XML 文件時,它會出現錯誤:
java.nio.file.NoSuchFileException: 123.xml
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:231)
at java.base/java.nio.file.Files.newByteChannel(Files.java:370)
at java.base/java.nio.file.Files.newByteChannel(Files.java:421)
at java.base/java.nio.file.Files.readAllBytes(Files.java:3205)
at java.base/java.nio.file.Files.readString(Files.java:3283)
at InputBox.Pfad(InputBox.java:26)
at InputBox.main(InputBox.java:10)
null
你試圖打開一個文件而不給它一個絕對路徑,只有當文件在當前工作目錄中時它才會工作
根據您的描述,您似乎沒有將 xml 文件的全名傳遞給您的函數。 所以試試
File f = chooser.getSelectedFile();
String path = f.getAbsolutePath + f.getName();
try {
content = Files.readString(path, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
希望這有幫助。
如前所述, File#getName() 丟失了路徑的目錄部分,因此它只會找到當前目錄中的文件。 要將File
對象轉換為Path
,只需使用其toPath()
方法:
Path path = chooser.getSelectedFile().toPath();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.