File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other common file operations (move, copy, delete, etc.).
- Get a File's Information
- Update a File's Information
- Download a File
- Upload a File
- Upload a large file in Chunks
- Upload a large file in Chunks (using helper method)
- Copy a File
- Delete a File
- Get Previous Versions of a File
- Upload a New Version of a File
- Download a Previous Version of a File
- Promote a Previous Version of a File
- Delete a Previous Version of a File
- Lock a File
- Unlock a File
- Create a Shared Link
- Get an Embed Link
- Get Thumbnail
- Create Metadata
- Get Metadata
- Update Metadata
- Delete Metadata
- Get All Metadata on File
Calling getInfo()
on a file returns a snapshot of the file's info.
BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();
Requesting information for only the fields you need with [getInfo(String...)
]
get-info2 can improve performance and reduce the size of the network request.
BoxFile file = new BoxFile(api, "id");
// Only get information about a few specific fields.
BoxFile.Info info = file.getInfo("size", "owned_by");
Updating a file's information is done by creating a new [BoxFile.Info
]
box-file-info object or updating an existing one, and then calling
updateInfo(BoxFile.Info)
.
BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.new Info();
info.setName("New Name");
file.updateInfo(info);
A file can be downloaded by calling download(OutputStream)
and
providing an OutputStream
where the file's contents will be written.
BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();
FileOutputStream stream = new FileOutputStream(info.getName());
file.download(stream);
stream.close();
Download progress can be tracked by providing a ProgressListener
to
download(OutputStream, ProgressListener)
. The ProgressListener
will then receive progress updates as the download completes.
BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();
FileOutputStream stream = new FileOutputStream(info.getName());
// Provide a ProgressListener to monitor the progress of the download.
file.download(stream, new ProgressListener() {
public void onProgressChanged(long numBytes, long totalBytes) {
double percentComplete = numBytes / totalBytes;
}
});
stream.close();
Files are uploaded to a folder by calling the
uploadFile(InputStream, String)
method.
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
FileInputStream stream = new FileInputStream("My File.txt");
BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt");
stream.close();
Upload progress can be tracked by providing the size of the file and a
ProgressListener
to
uploadFile(InputStream, String, long, ProgressListener)
. The
ProgressListener
will then receive progress updates as the upload completes.
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
FileInputStream stream = new FileInputStream("My File.txt");
BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt", 1024, new ProgressListener() {
public void onProgressChanged(long numBytes, long totalBytes) {
double percentComplete = numBytes / totalBytes;
}
});
stream.close();
An upload session can be created with the createUploadSession(fileName, fileSize)
method to
upload a large file in chunks.
//Create the upload session
BoxFile file = new BoxFile(api, "id");
BoxFileUploadSession.Info sessionInfo = file.createUploadSession("My_Large_File.txt", fileSize);
//Get the session resource from the session info
BoxFileUploadSession session = sessionInfo.getResource();
//Create the Message Digest for the whole file
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException ae) {
throw new BoxAPIException("Digest algorithm not found", ae);
}
Once the upload session is created, using that session the large file can be uploaded in chuncks with the
uploadPart(partId, stream, offset, partSize, totalSizeOfFile)
method of the session instance.
If there is a failure in uploading any of the parts,
the failed part can be uploaded again without affecting the other parts.
//Reading a large file
FileInputStream fis = new FileInputStream("My_Large_File.txt");
//Create the digest input stream to calculate the digest for the whole file.
DigestInputStream dis = new DigestInputStream(fis, digest);
List<BoxFileUploadSessionPart> parts = new ArrayList<BoxFileUploadSessionPart>();
//Get the part size. Each uploaded part should match the part size returned as part of the upload session.
//The last part of the file can be less than part size if the remaining bytes of the last part is less than
//the given part size
long partSize = sessionInfo.getPartSize();
//Start byte of the part
long offset = 0;
//Overall of bytes processed so far
long processed = 0;
while (processed < fileSize) {
long diff = fileSize - processed;
//The size last part of the file can be lesser than the part size.
if (diff < partSize) {
partSize = diff;
}
//Generate a unique partId
String partId = LargeFileUpload.generateHex();
//Upload a part. It can be uploaded asynchorously
BoxFileUploadSessionPart part = session.uploadPart(partId, dis, offset, partSize, fileSize);
parts.add(part);
//Increase the offset and proceesed bytes to calculate the Content-Range header.
processed += partSize;
offset += partSize;
}
At any point in time, the list of parts that are being uploaded successfully can be retrivied with the
listParts(offset, limit)
method of the session instance.
//The following snippet retrives first 1000 parts that are uploaded. Both can be modified based on the needs.
BoxFileUploadSessionPartList partList = session.listParts(0, 1000);
List<BoxFileUploadSessionPart> parts = partList.getEntries();
Once all the parts are uploaded successfully. the upload sessiion can be commited with the
commit(digest, parts, attributes, ifMatch, ifNoneMatch)
method.
//Creates the file hash
byte[] digestBytes = digest.digest();
//Base64 encoding of the hash
String digestStr = Base64.encode(digestBytes);
//Commit the upload session. If there is a failure, abort the commit.
BoxFile.Info fileInfo = session.commit(digestStr, parts, null, null, null);
The upload session can be aborted at any time with the abort()
method of the session instance.
session.abort();
The upload session status can be retrived at any time with the getstatus()
method.
This call will update the parts processed and other information in the session info instance.
BoxFileUploadSession.Info updatedSessionInfo = session.getStatus();
A large file can be uploaded with the uploadLargeFile(InputStream, fileName, fileSize)
method.
File myFile = new File("My Large_File.txt");
FileInputStream stream = new FileInputStream(myFile);
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
BoxFile.Info fileInfo = rootFolder.uploadLargeFile(inputStream, "My_Large_File.txt", myFile.length());
A file can be copied to a new folder and optionally be renamed with the
copy(BoxFolder)
and copy(BoxFolder, String)
methods.
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
BoxFile file = new BoxFile(api, "id");
BoxFile.Info copiedFileInfo = file.copy(rootFolder, "New Name");
Calling the delete()
method will move the file to the user's trash.
BoxFile file = new BoxFile(api, "id");
file.delete();
For users with premium accounts, versions of a file can be retrieved with the
getVersions()
method.
BoxFile file = new BoxFile(api, "id");
List<BoxFileVersion> versions = file.getVersions();
for (BoxFileVersion version : versions) {
System.out.format("SHA1 of \"%s\": %s\n", item.getName(), version.getSha1());
}
New versions of a file can be uploaded with the
uploadVersion(InputStream)
method.
BoxFile file = new BoxFile(api, "id");
FileInputStream stream = new FileInputStream("My File.txt");
file.uploadVersion(stream);
For users with premium accounts, previous versions of a file can be downloaded
by calling download(OutputStream)
.
BoxFile file = new BoxFile(api, "id");
List<BoxFileVersion> versions = file.getVersions();
BoxFileVersion firstVersion = versions.get(0);
FileOutputStream stream = new FileOutputStream(firstVersion.getName());
firstVersion.download(stream);
stream.close();
A previous version of a file can be promoted with the promote()
method to become the current version of the file.
BoxFile file = new BoxFile(api, "id");
List<BoxFileVersion> versions = file.getVersions();
BoxFileVersion firstVersion = versions.get(0);
firstVersion.promote();
A version of a file can be deleted and moved to the trash by calling
delete()
.
BoxFile file = new BoxFile(api, "id");
List<BoxFileVersion> versions = file.getVersions();
BoxFileVersion firstVersion = versions.get(0);
firstVersion.delete();
An upload session can be created with the createUploadSession(fileSize)
method to upload new version of a large file in chunks.
BoxFile file = new BoxFile(api, "id");
BoxFileUploadSession.Info session = file.createUploadSession(fileSize);
//Get the session resource from the session info
BoxFileUploadSession session = sessionInfo.getResource();
//Create the Message Digest for the whole file
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException ae) {
throw new BoxAPIException("Digest algorithm not found", ae);
}
Once the upload session is created, the large file can be uploaded in chuncks with the
uploadPart(partId, stream, offset, partSize, totalSizeOfFile)
method of the session instance.
If there is a failure in uploading any of the parts, the failed part can be uploaded again without
affecting the other parts.
//Reading a large file
FileInputStream fis = new FileInputStream("My_Large_File.txt");
//Create the digest input stream to calculate the digest for the whole file.
DigestInputStream dis = new DigestInputStream(fis, digest);
List<BoxFileUploadSessionPart> parts = new ArrayList<BoxFileUploadSessionPart>();
//Get the part size. Each uploaded part should match the part size returned as part of the upload session.
//The last part of the file can be less than part size if the remaining bytes of the last part is less than
//the given part size
long partSize = sessionInfo.getPartSize();
//Start byte of the part
long offset = 0;
//Overall of bytes processed so far
long processed = 0;
while (processed < fileSize) {
long diff = fileSize - processed;
//The size last part of the file can be lesser than the part size.
if (diff < partSize) {
partSize = diff;
}
//Generate a unique partId
String partId = LargeFileUpload.generateHex();
//Upload a part. It can be uploaded asynchorously
BoxFileUploadSessionPart part = session.uploadPart(partId, dis, offset, partSize, fileSize);
parts.add(part);
//Increase the offset and proceesed bytes to calculate the Content-Range header.
processed += partSize;
offset += partSize;
}
At any point in time, the list of parts that are being uploaded successfully can be retrivied with the
listParts(offset, limit)
method of the session instance.
//The following snippet retrives first 1000 parts that are uploaded. Both can be modified based on the needs.
BoxFileUploadSessionPartList partList = session.listParts(0, 1000);
List<BoxFileUploadSessionPart> parts = partList.getEntries();
Once all the parts are uploaded successfully. the upload session can be commited with the
commit(digest, parts, attributes, ifMatch, ifNoneMatch)
method.
//Creates the file hash
byte[] digestBytes = digest.digest();
//Base64 encoding of the hash
String digestStr = Base64.encode(digestBytes);
//Commit the upload session. If there is a failure, abort the commit.
BoxFile.Info fileInfo = session.commit(digestStr, parts, null, null, null);
The upload session can be aborted at any time with the abort()
method of the session instance.
session.abort();
The upload session status can be retrived at any time with the getstatus()
method.
This call will update the parts processed and other information in the session info instance.
BoxFileUploadSession.Info sessionInfo = session.getStatus();
New versions of a large file can be uploaded with the
uploadLargeFile(InputStream, fileSize)
method.
File myFile = new File("My File.txt");
FileInputStream stream = new FileInputStream(myFile);
BoxFile file = new BoxFile(api, "id");
BoxFile.Info versionedFileInfo = file.uploadLargeFile(inputStream, myFile.length());
A file can be locked by calling lock(Date)
.
BoxFile file = new BoxFile(api, "id");
Date expiresAt = new Date();
file.lock(expiresAt);
A file can be unlocked by calling unlock()
.
BoxFile file = new BoxFile(api, "id");
file.unlock();
A shared link for a file can be generated by calling createSharedLink(BoxSharedLink.Access, Date, BoxSharedLink.Permissions)
.
BoxFile file = new BoxFile(api, "id");
BoxSharedLink.Permissions permissions = new BoxSharedLink.Permissions();
permissions.setCanDownload(true);
permissions.setCanPreview(true);
Date unshareDate = new Date();
BoxSharedLink sharedLink = file.createSharedLink(BoxSharedLink.Access.OPEN, unshareDate, permissions);
A file embed link can be generated by calling getPreviewLink()
.
BoxFile file = new BoxFile(api, "id");
URL embedLink = file.getPreviewLink();
A thumbnail for a file can be retrieved by calling getThumbnail(BoxFile.ThumbnailFileType, int, int, int)
.
BoxFile file = new BoxFile(api, "id");
byte[] thumbnail = file.getThumbnail(BoxFile.ThumbnailFileType.PNG, 256, 256, 256, 256)
Metadata can be created on a file by calling createMetadata(Metadata)
, createMetadata(String, Metadata)
, or createMetadata(String, String, Metadata)
BoxFile file = new BoxFile(api, "id");
file.createMetadata(new Metadata().add("/foo", "bar"));
Retrieve a files Metadata by calling getMetadata()
, getMetadata(String)
, or getMetadata(String, String)
.
BoxFile file = new BoxFile(api, "id");
file.getMetadata();
Update a files Metadata by calling updateMetadata(Metadata)
.
BoxFile file = new BoxFile(api, "id");
file.updateMetadata(new Metadata().add("/foo", "bar"));
A files Metadata can be deleted by calling deleteMetadata()
, deleteMetadata(String)
, or deleteMetadata(String, String)
.
BoxFile file = new BoxFile(api, "id");
file.deleteMetadata();
getAllMetadata(String...)
method will return an iterable that will page through all of the metadata associated with the file.
BoxFile file = new BoxFile(api, "id");
Iterable<Metadata> metadataList = file.getAllMetadata("name", "description");
for (Metadata metadata : metadataList) {
// Do something with the metadata.
}