I'm working on an app that needs to send an automatic email on button click. the problem I am currently have is that I need to read a json file and when I pass the path of the json stored in assets into into a new FileReader() I get a file not found Exception. here is how I am getting the path. (wondering if Uri.parse().toString is redundant):
private static final String CLIENT_SECRET_PATH =
Uri.parse("file:///android_asset/raw/sample/***.json").toString()
and here is the method I am passing it into:
sClientSecrets = GoogleClientSecrets
.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));
the json file that I am attemping to access is in my apps asset folder under the app root in android project directory (/app/assets/)
I am not sure what I am doing wrong here but I'm sure it is something simple. please help point me in the right direction.
You should not access the assets using direct file path.
The files are packed and the location will change on each device.
You need to use a helper function to get the assets path
getAssets().open()
See this post for more information.
Keep your file directly inside assets directory rather then raw-sample.
And then file path will be like this
private static final String CLIENT_SECRET_PATH =
Uri.parse("file:///android_asset/***.json").toString()
hope your problem will be solved..
You can use this function to get JSON string from assets and pass that string to the FileReader.
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
#Rohit i was able to use the method you provided as a starting point. the only issue with it was that the gmail api that i am using requires a Reader as its parameter, not a string. here is what i did. and i am no longer getting filenotfoundexception. thank you very much.
public InputStreamReader getJsonStreamReader(String file){
InputStreamReader reader = null;
try {
InputStream in = getAssets().open(file);
reader = new InputStreamReader(in);
}catch(IOException ioe){
Log.e("launch", "error : " + ioe);
}
return reader;
}
Related
I have been trying to download files/whole directory from publicly available google drive link URL using Java. I am able to read files which are present in my google drive using google drive libraries but I am not able to understand how to pass google drive link URL.
Also, I tried to use typical method of downloading files from URL but it produced error java.io.IOException: Server returned HTTP response code: 400 for URL.
URL url;
URLConnection con;
DataInputStream dis;
FileOutputStream fos;
byte[] fileData;
try {
url = new URL("https://drive.google.com/drive/folders/<some-alphanumeric-code>/<file-name>"); //File Location goes here
con = url.openConnection(); // open the url connection.
dis = new DataInputStream(con.getInputStream());
fileData = new byte[con.getContentLength()];
for (int q = 0; q < fileData.length; q++) {
fileData[q] = dis.readByte();
}
dis.close(); // close the data input stream
fos = new FileOutputStream(new File("/Users/abhijeetkunwar/file.png")); //FILE Save Location goes here
fos.write(fileData); // write out the file we want to save.
fos.close(); // close the output stream writer
}
catch(Exception m) {
System.out.println(m);
}
Kindly suggest the solution please.
The link you are using contains the folder id, the folder should also be readable by everyone.
In this instance you can use the files.list method from the Google drive api and access it using 'folderid' in parents which will return a list of all of the files within that folder.
For this to work the folder needs to be public to viewers which yours seem to be, after our conversation in chat.
I have a Java method that takes byte array and String value as arguments and returns a File object. This is the code
public File createTempFile(byte[] byteArray, String fileName) throws IOException {
String prefix = FilenameUtils.getBaseName(fileName);
String suffix = getMimeType(byteArray);
File tempFile = File.createTempFile(prefix, suffix, null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
fos.write(byteArray);
fos.close();
return tempFile;
}
When I try to run it like this
File myFile = tiedostoService.createTempFile(tiedosto.getContent(), attachment.getFileName());
I get an IOException like this
java.io.IOException: Unable to create temporary file, C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image\png
at java.io.File$TempDirectory.generateFile(File.java:1921)
at java.io.File.createTempFile(File.java:2010)
From the stacktrace. it can be seen that it's trying to create a file like C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image\png
and not C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image.png
How can I fix this? I'd really appreciate any sort of help.
'image/png' is a Mime Type. See all MimeTypes in java here
Write a util which converts mimetype to file extension. Hopefully this will help.
I think there is an extra \ in your suffix string, could you try debug and see the actual value of the suffix?
I tried to run:
String suffix = "\\png";
and got the same error, but if I do
String suffix = ".png";
no error creating the temp file, notice that you need to add a dot in the suffix...
HttpExchange exchange;
OutputStream responseBody = null;
try{
File fileVal = new File(file);
InputStream inVal = new FileInputStream(fileVal);
exchange.sendResponseHeaders(HTTP_OK, fileVal.length());
responseBody = exchange.getResponseBody();
int read;
byte[] buffer = new byte[4096];
while ((readVal = inVal.read(buffer)) != -1){
responseBody.write(buffer, 0, readVal);
}
} catch (FileNotFoundException e){
//uh-oh, the file doesn't exist
} catch (IOException e){
//uh-oh, there was a problem reading the file or sending the response
} finally {
if (responseBody != null){
responseBody.close();
}
}
I am tring to upload large video file as chunks .while doing the operation I am getting the following error.
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.io.File(org.springframework.web.multipart.commons.CommonsMultipartFile)
any anyone guide me to solve this.
File fileVal = new File(file);
Here file is org.springframework.web.multipart.commons.CommonsMultipartFile type and you are trying to create File object by passing CommonsMultipartFile object in constructor and File class does not have constructor of CommonsMultipartFile type.
Check here for File Class Constructor
You Need to get Bytes from file object and create a java.io.File object.
Convert MultiPartFile into File
The error message descripes the failure perfectly. There is no constructor for the class File that accept a parameter of the type org.springframework.web.multipart.commons.CommonsMultipartFile.
Try using the path to the file you want to open. For example:
String path = "/path/to/your/file.txt";
File fileVal = new File(path);
Alternatively you can use the getInputStream() method from CommonsMultipartFile.
InputStream inVal = file.getInputStream();
I am trying to send Files in fragments using DatagramPackets in Java (part of an assignemt.) When I am trying to save the incoming File I get access denied error, but I believe that it is not a permissions issue.
Here is the brunt of it:
I let the user sending the file to choose it using FileChooser. And create a new Message object.
//....
File f = content.showFileChooser();
byte type = Byte.parseByte("4");
Message m;
try {
if (mode == 1){
m = new Message(f, content.getServerData().getFragmentSize(), (short) (sentMessages.size()+1), type);
serverThread.send(m);
}
//...
During Message creation the file gets split up into byte arrays, where the size of each array is predetermined by the user. The code is quite lengthy so I am not going to post the chopping process, but this is how I convert the File object into a big byte[] which then gets chopped up
Path p = Paths.get(file.getAbsolutePath());
this.rawData = Files.readAllBytes(p);
After the Message is created and chopped up into byte arrays I send them using DatagramPackets. The other side then uses those to create a new Message object. Once all fragments arrive rawData is extracted from the Message object again. The problem believe lies here:
Message m = receivedMessages.get(msgIndex-1);
byte[] fileData = m.getFile();
if (fileData != null){
System.out.println("All file fragments received.");
content.append("Received a file in" + m.getFragmentCount()+" fragments. Choose directory. " ,1);
//I BELIEVE THIS TO BE THE CRITICAL POINT
String filePath = content.chooseDirectory();
if (filePath == null)
return;
FileOutputStream fos;
try {
fos = new FileOutputStream(filePath);
fos.write(fileData);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Once all fragments arrive I let the user select a directory using FileChooser with DIRECTORY_ONLY choice mode. As I understand, FileOutputStream requires a full path for the new File. Do I have to send the file name and extension separately or can it be extracted from the received File data?
You are writing directory path to filePath, then try to open that directory with FileOutputStream. No wonder that doesn't work, you have to specify the filename too.
String filename = "myfile.txt"; //Or receive and set this some other way
File outFile = new File(filePath, filename);
fos = new FileOutputStream(outFile);
I don't see you sending/receiving the filename anywhere, though. You'll need to either make it constant or transfer it along with file contents.
I need to create a File object out of a file path to an image that is contained in a jar file after creating a jar file. If tried using:
URL url = getClass().getResource("/resources/images/image.jpg");
File imageFile = new File(url.toURI());
but it doesn't work. Does anyone know of another way to do it?
To create a file on Android from a resource or raw file I do this:
try{
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Don't forget to close your streams etc
This should work.
String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));
Usually, you can't directly get a java.io.File object, since there is no physical file for an entry within a compressed archive. Either you live with a stream (which is best most in the cases, since every good API can work with streams) or you can create a temporary file:
URL imageResource = getClass().getResource("image.gif");
File imageFile = File.createTempFile(
FilenameUtils.getBaseName(imageResource.getFile()),
FilenameUtils.getExtension(imageResource.getFile()));
IOUtils.copy(imageResource.openStream(),
FileUtils.openOutputStream(imageFile));
You cannot create a File object to a reference inside an archive. If you absolutely need a File object, you will need to extract the file to a temporary location first. On the other hand, most good API's will also take an input stream instead, which you can get for a file in an archive.