Error in URL.getFile() - java-7

I am trying to open a file from URL.
Object of URL is created with getResource() method of ClassLoader.
Output URL returned from getResource() method is =
file:/C:/users/
After using URL.getFile() method which returns String as " /C:/users/ " it removes "file:" only not the "/ "
This / gives me a error in opening a file using new FileInputStream.
Error : FileNotFoundException
" / " in the starting of the filename causes the same problem in getting the path object.
Here , value of directory is retrieved from the URL.getResource().getFile()
Path Dest = Paths.get(Directory);
Error received is :
java.nio.file.InvalidPathException: Illegal char <:> at index 2: /C:/Users/
is anyone face such issue ?

Don't use URL.getFile(), it returns the "file" part of the URL, which is not the same as a file or path name of a file on disk. (It looks like it, but there are many ways in which there is a mismatch, as you have discovered.) Instead, call URL.toURI() and pass the resulting URI object to Paths.get()
That should work, as long as your URL points to a real file and not to a resource inside a jar file.
Example:
URL url = getClass().getResource("/some/resource/path");
Path dest = Paths.get(url.toURI());

The problem is that your result path contains leading /.
Try:
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Path path = Paths.get(loader.getResource(filename).toURI());

Related

How to differentiate between a network path and absolute path and read a file from network path in java

I have a field where a user can specify an absolute path or network path.
In the Excel Folder Path user can give an absolute path or network path.
Absolute Path -> C:\ExcelExtractor
Network Path -> file://LAPTOP-83N1BUOI/Users/d_avi/OneDrive/Documents
Also will the network path start with file : or will it start with // or \
In my java code i get the value of Excel Folder Path
Here is my sample java code.
public class Testing {
public static void main(String[] args) {
File file = new File("file://LAPTOP-83N1BUOI/Users/d_avi/OneDrive/Documents");
String fileName = file.getName();
System.out.println("Is file " + file.isFile());
System.out.println("Directory " + file.isDirectory());
System.out.println("Absolute " + file.isAbsolute());
System.out.println("fileName is " + fileName);
System.out.println("Can Read " + file.canRead());
System.out.println("Can Write " + file.canWrite());
File file1 = new File("D:\\File Testing");
System.out.println("Directory" + file1.isDirectory());
System.out.println("Absolute" + file1.isAbsolute());
}
Here is the output of the code
Is file false -> this condition is clear, because the path given is till a folder
Directory false
Absolute false
fileName is Documents
Can Read false
Can Write false
Directory true
Absolute true
I have given all the sharing and permissions to the Documents folder, but still isDirectory() returns false, canRead() returns false, canWrite () returns false.
I agree with the condition Is file returning false because the path is given till a directory
Need help and suggestions on the following
- How to decide whether it is network path
- How to read a file from network path
- How to create a new folder in network path and copy a file to that folder

PyQt6 adding image resource to QDocument

I am porting an application from PyQT5 to PyQt6. It displays multiple images in a QTextEdit. I need to add an image resource to QTextEdit QTextDocument but am getting an error.
TypeError: addResource(self, int, QUrl, Any): argument 1 has unexpected type 'ResourceType'
Method variables are img: Dictionary, counter: Integer, text_edit: QTextEdit
path_ = self.app.project_path
if img['mediapath'][0] == "/":
path_ = path_ + img['mediapath']
else:
path_ = img['mediapath'][7:]
document = text_edit.document()
image = QtGui.QImageReader(path_).read()
image = image.copy(img['x1'], img['y1'], img['width'], img['height'])
# Need unique image names or the same image from the same path is reproduced
imagename = self.app.project_path + '/images/' + str(counter) + '-' + img['mediapath']
url = QtCore.QUrl(imagename)
document.addResource(QtGui.QTextDocument.ResourceType.ImageResource, url, QtCore.QVariant(image))
The Qt6 documentation at https://doc.qt.io/qt-6/qtextdocument.html#addResource says:
For example, you can add an image as a resource in order to reference it from within the document:
document->addResource(QTextDocument::ImageResource,
QUrl("mydata://image.png"), QVariant(image));
Note: I have tried the following which matches the Qt6 documentation:
document.addResource(QtGui.QTextDocument.ImageResource, url, QtCore.QVariant(image))
This gives the error: AttributeError: type object 'QTextDocument' has no attribute 'ImageResource'
I found a solution that works, and I think, either the QT6 documentation needs to be updated, or the PyQt6 implementation of the documentation needs to be developed.
The required Integer is stored in the value attribute:
document.addResource(QtGui.QTextDocument.ResourceType.ImageResource.value, url, QtCore.QVariant(image))
QVariant method is not required, simpler code below:
document.addResource(QtGui.QTextDocument.ResourceType.ImageResource.value, url, image)

How to save a PDF file downloaded as byte[] array obtained from a Rest WS

I trying to save a PDF file, previously obtained from a REST WS as byte[] array.
byte[] response = await caller.DownloadFile(url);
string documentPath = FileSystem.CacheDirectory;
string fileName = "downloadfile.pdf";
string path = Path.Combine(documentPath, fileName);
File.WriteAllBytes(path, response);
My actual implementation don't shows any errors but when I looking for the file on cache folder, nothing are there, just a empty folder. Also try put the file in FileSystem.AppDataDirectory and Environment.GetFolderPath(Environment.SpecialFolder.Personal) but there are no files in any folder
What I'm missing?
Thank's in advance.
string documentPath = FileSystem.CacheDirectory;
string fileName = "downloadfile.pdf";
string path = Path.Combine(documentPath, fileName);
the path will like
"/data/user/0/packagename/cache/downloadfile.pdf"
As you save it to Internal Storage,you couldn't see the files without root permission,if you want to view it,you could use adb tool (application signed by Android Debug)
adb shell
run-as packagename
cd /data/data/packagename
cd cache
ls
then you could see the downloadfile.pdf
or you could save it to External storage,then you could find it in your device File Manager:
//"/storage/emulated/0/Android/data/packagename/files/downloadfile.pdf"
string path = Android.App.Application.Context.GetExternalFilesDir(null).ToString();

Wrong filename when downloading file whose name contains double quote(") from Springboot server

The code for setting filename for the file to be downloaded :
String originalFileNameDecoded = URLDecoder.decode(originalFileName, "UTF-8");
URI uri = new URI(null, null, originalFileNameDecoded, null);
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"" + uri.toASCIIString() + "\"")
.contentLength(resource.contentLength())
.contentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
The reason why first decode the filename is because the originalFileName may contains URL encoded characters.
For files with regular names (only number and English letter), it works fine. However, when I try to download a file with name like pic201;9050.814,3"731(copy).png in the browser (chrome on linux), the filename becomes pic201;9050.814,3_731(copy).png.
I used to believe it is the browser behaviour, but I tried it in Edge and the same situation happened again.
So I wonder if there is something wrong with my code or something else happened.

How to get the downloaded xlsx file from the api endpoint in karate?

I have an endpoint that downloads an xlsx file. In my test, I need to check the content of the file (not comparing the file with another file, but reading the content and checking). I am using karate framework for testing and I am trying to use apache POI for working with the excel sheet. However, the response I get from karate when calling the download endpoint is a String. For creating an excel file with POI I need an InputStream or the path to the actual file. I have tried the conversion, but it does not work.
I guess I am missing some connection here, or maybe the conversion is bad, I am new to karate and to the whole thing.
I appreciate any help, thanks!
Given url baseUrl
Given path downloadURI
When method GET
Then status 200
And match header Content-disposition contains 'attachment'
And match header Content-disposition contains 'example.xlsx'
And match header Content-Type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
* def value= FileChecker.createExcelFile(response)
* print value
And the Java code:
public static String createExcelFile(String excel) throws IOException, InvalidFormatException {
InputStream stream = IOUtils.toInputStream(excel, Charset.forName("UTF-8"));
Workbook workbook = WorkbookFactory.create(stream);
return ("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
}
When running the scenario, I get the following error:
javascript evaluation failed: FileChecker.createExcelFile(response), java.io.IOException: Failed to read zip entry source
When testing the same endpoint in Postman, I am getting a valid excelsheet.
In Karate 0.9.X onwards you have a responseBytes variable which will be raw bytes, which may be what you need.
* def value = FileChecker.createExcelFile(responseBytes)
And you can change your method signature to be:
public static String createExcelFile(byte[] excel) {}
You should be easily able to convert a byte array to an InputStream and take it from there.
P.S. just saying that it "works in Postman" is not helpful :P
TO download zip file from Karate tests as binary bite array
Scenario: To verify and get the ADCI Uri from deployment
Given url basicURL + DeployUri +ArtifactUri
And headers {authorization:'#(authToken)',accept:'application/json',tenant:'#(tenantUUId)',Content-Type:'application/zip'}
When method get
Then status 200
And def responsebytes = responseBytes

Resources