I created a raw Android resource directory in res and added cars.json to it. It shows up on my package explorer. When I try to call
File file = new File("raw/cars.json")
I get a FileNotFoundException. I've tried using simply cars.json and even the entire path to the file but I get the same results.
Any suggestions?
To get a resource from the raw directory call getResources().openRawResource(resourceName).
This will give you a InputStream
You can use this function directly:
private String getJsonStringFromRaw(filenmae)
{
String jsonString = null;
try {
InputStream inputStream= getAssets().open(filename);
int size = inputStream.available();
byte[] buffer= new byte[size];
inputStream.read(buffer);
inputStream.close();
jsonString = new String(buffer, "UTF-8"); }
catch (IOException e)
{
e.printStackTrace();
return null;
}
return jsonString;
}
You can access json data by iterating through the json object below. JSONObject obj = new JSONObject(getJsonStringFronRaw("cars.json"))
Retrieving resource from the raw directory can be achieved with openRawResources a sub class of getResources, this takes in a resource id (your json file) and returns a InputStream.
InputStream myInput=getResources().openRawResource(R.raw.your_json);
If you need more info, here is the google documention
Related
I am building am app the will work offline.
I download the json to a file in the sdcard. then when I try and load it using gson and map it with POJO class I get error:
read the file:
File newList = new File(rootFolder.getParent(), "custom_list.new.dat");
String customListStr = Utils.readTextFile(newList);
public static String readTextFile(File file) throws IOException {
FileInputStream reader = new FileInputStream(file);
StringBuffer data = new StringBuffer("");
byte[] buffer = new byte[1024];
while (reader.read(buffer) != -1)
data.append(new String(buffer));
reader.close();
return data.toString();
}
try to load it
//Load json file to Model
Gson gson = new GsonBuilder().create();
final MoviePojo response = gson.fromJson(customListStr, MoviePojo.class);
int size = response.getContentList().size();
: Error: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 3205 path $
The error shows you, in the text, that the JSON you have downloaded has an error in its structure MalformedJsonException, "Malformed". Check the JSON file, from top to bottom, may be some of this ("{", "[", ",", ":" ) characters are missing or has more than the quantity it needs.
Good luck.
Hi i have been trying to upload image file in Play Framework. I have been trying out with Java File Upload since morning but unable to do so. I have seen [JavaFileUpload][1] tutorial available on framework website. But i am still not successful. Here is my code which i am trying to run:
Http.MultipartFormData body = request().body().asMultipartFormData();
List<Http.MultipartFormData.FilePart> fileParts = body.getFiles();
for (Http.MultipartFormData.FilePart filePart : fileParts) {
String filename = filePart.getFilename();
File file = filePart.getFile(); //error comes on this line
if (filePart.getFilename().toLowerCase().endsWith(".png")) {
//saving here but how?
} else {
return badRequest("Invalid request, only PNGs are allowed.");
}
}
but problem is that whenever i try to get the file i am having this conversion error:
java.lang.Object cannot be converted to java.io.File
Anyone can guide me in the direction? if we see the official document there is no proper documentation on how to upload multiple files. If anyone can show me some website which can helps me in that direction that will be also helpful
I'm using Play 2.4 and
FilePart filePart = request().body().asMultipartFormData()
.getFile("myFileKey");
File file = filePart.getFile();
With Play 2.2 I used for multiple file uploads:
MultipartFormData mfd = request().body().asMultipartFormData();
List<FilePart> filePartList = mfd.getFiles();
FilePart filePart = filePartList.get(0);
So after lots of trouble i was able to figure out the answer to my question. Here i am going to post the answer so it helps other people searching the answer to the same problem i faced
The controller function call which will upload the files looks like this:
Http.MultipartFormData body = request().body().asMultipartFormData();
List<Http.MultipartFormData.FilePart> fileParts = body.getFiles();
for (Http.MultipartFormData.FilePart filePart : fileParts) {
if (filePart.getFilename().toLowerCase().endsWith(".png")) {
String filename = filePart.getFilename();
Files.write(Paths.get(filename + ".png"), readContentIntoByteArray((File) filePart.getFile()));
} else {
return badRequest("Invalid request, only PNGs are allowed.");
}
}
I am using a function call to read the content of the file into byte array and save them inside the file:
private static byte[] readContentIntoByteArray(File file) {
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return bFile;
}
Remember you can choose whatever the path you want to save the file at Paths.get(filename + ".png")
I'm trying to download a file from S3 using AWS SDK for Java and store the particular file in a local directory in my PC.
The code I wrote for downloading the object is:
public void download(String key) {
S3Object obj=s3Client.getObject(new GetObjectRequest(bucketname,key));
}
But what I actually want to do is to pass the local path as a parameter instead of key and store the downloaded file obj in that particular directory say /tmp/AWSStorage/ in my linux box.
Can you please suggest a way of doing it?
I used:
s3Client.getObject(new GetObjectRequest(bucket,key),file);
It worked fine.
There is an API to directly download file to local path
ObjectMetadata getObject(GetObjectRequest getObjectRequest,
File destinationFile)
With Java >=1.6, you can directly copy the files downloaded to local directory without any problem of file corruption. Check the code:
S3Object fetchFile = s3.getObject(new GetObjectRequest(bucketName, fileName));
final BufferedInputStream i = new BufferedInputStream(fetchFile.getObjectContent());
InputStream objectData = fetchFile.getObjectContent();
Files.copy(objectData, new File("D:\\" + fileName).toPath()); //location to local path
objectData.close();
With Java 1.6 and above, you can directly specify path in Files.copy function.
You can use obj.getDataInputStream() to get the file. And then org.apache.commons.io.IOUtils copy method to copy.
S3Object obj=s3Client.getObject(new GetObjectRequest(bucketname,key));
File file=new File("/tmp/AWSStorage/"+key);
// if the directory does not exist, create it
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
And then you can use either of following.
try {
IOUtils.copy(obj.getDataInputStream(), new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
OR
BufferedReader reader=null;
BufferedWriter out=null;
String data = null;
try {
reader = new BufferedReader(new InputStreamReader(fileObj.getDataInputStream()));
out = new BufferedWriter (new FileWriter(file));
while ((data = reader.readLine()) != null) {
out.write(data);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
reader.close();
out.close();
}
In the line S3Object obj=s3Client.getObject(new GetObjectRequest(bucketname,key));
bucketname is the S3BucketName and Key is the object name, it is not a local file path.
Key - is the combination of common-prefix / objectname
i.e. if you file is saved at root of bucket then only name of the object will be the key i.e. myfile.txt
but if your file is save like myfolder1/myfolder2/myfile.txt then
myfolder1/myfolder is your common-prefix and myfile.txt is objectname.
S3Object obj=s3Client.getObject(new GetObjectRequest(bucketname,"myfolder1/myfolder2/myfile.txt"));
I am attempting to download a file automatically. I know the link as I have already parsed it from the RSS XML file. Is there a simple noob friendly way of doing this?
Since my previous edit I have been informed that as long as I keep the file name the same I will be able to do this this is the code I have so far (I should have mentioned previously that this is for a bukkit plugin however the plugin)
public void getFile (String url) {
try{
BufferedInputStream in = new BufferedInputStream(new
URL("http://dev.bukkit.org/media/files/706/595/Kustom-Warn.jar").openStream());
FileOutputStream fileOutputStream = new FileOutputStream(plugin.getDataFolder().getAbsolutePath() + "/KustomWarn.jar");
logger.severe(String.valueOf(plugin.getDataFolder().getAbsolutePath()));
BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream,1024);
byte data[] = new byte[1024];
while(in.read(data,0,1024)>=0)
{
outputStream.write(data);
}
outputStream.close();
in.close();
}catch (Exception e){
logger.severe("Error: " + e.getMessage());
}
}
If you mean to copy a file from a site to a local file then you can use java.nio.file
Files.copy(new URL("http://host/site/filename").openStream(), Paths.get(localfile));
Use URL.openStream to open the stream and Java NIO (New I/O) to read efficiently.
I am calling a file glassShader.vert from the following method and it gives me FileNotFoundException error
The complicated issue is that the class GLGridRenderer that contains this method lies in the directory GridLogin which is in turn inside the package com.jasfiddle.AmazingInterface
So to address the directory, it would be com.jasfiddle.AmazingInterface.GridLogin
But I don't know how to call shader.vert which is inside GridLogin
public static String readShaderFile(String filepath) throws IOException {
FileInputStream stream = new FileInputStream(new File(filepath));
try{
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
return Charset.defaultCharset().decode(bb).toString();
}
finally{
stream.close();
}
}
other than raw you can also use asset folder see link ....
try {
// get input stream for text
InputStream is = getAssets().open("text.txt");
// check size
int size = is.available();
// create buffer for IO
byte[] buffer = new byte[size];
// get data to buffer
is.read(buffer);
// close stream
is.close();
}
catch (IOException ex) {
return;
}
Files that you want to read should not be put in a package. They should be packaged as resources or assets. For instance, with a data file, put it in the res/raw folder and give it a legal resource name. Then you can open an input stream if you have a Context (such as your Activity class or a View class).
InputStream stream = context.getResources().openRawResource(R.raw.filepath);
(This would be if you named the file res/raw/filepath.dat. You'd probably want a more meaningful name. If you want the name to be a variable, then you can obtain the resource ID using:
int resId = context.getResources.getIdentifier(filepath, "raw", context.getPackageName());