[英]Working with file from google cloud storage
我將代碼重構為可與GCS一起使用,而不僅僅是在本地,我正在解析xml文件。
我的原始代碼:
File file = new File("localpath.xml");
DocumentBuilder docBuilder = DocumentBuilderFactory.instance().newDocumentBuilder();
Document d = docBuilder.parse(file);
但是,由於使用gcs,現在看起來像這樣:
Blob blob = storage.get(bucketName, filePath);
ReadChannel readChannel = blob.reader();
既然我的readChannel中包含內容,如何將其轉換為File對象? 有沒有一種方法可以解決此問題而無需重新構造我的所有代碼?
除了應該轉換為Java File對象外,我們還應該了解ReadChannel對象具有read方法(請參閱https://googleapis.dev/java/google-cloud-clients/0.97.0-alpha/com/google/cloud/ ReadChannel.html )。 通過read()方法,您可以填充ByteBuffer對象。 此時,您現在已將Java應用程序中GCS blob的內容作為ByteBuffer對象。
給定ByteBuffer,您現在可以使用array()方法以byte []數組的形式訪問數據( https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html #array() )。 現在您有了一個byte []數組,可以將其包裝在輸入流( https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html )中。
最后...我們已經從ReadChannel-> InputStream出發了,您可以使用DocumentBuilder parse()方法解析內容,該方法具有一個需要InputStream的重載...
...稍后...
也許一個簡單的故事是認識到給定Blob對象,我們可以使用Blob.getContent()直接進入byte []數組。 一旦有了byte [],就可以創建DocumentBuilder.parse()所需的ByteArrayInputStream。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.