To download files from SharePoint using Java, you can use the SharePoint REST API. Here is an example code that demonstrates how to download a file from SharePoint using Java:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class SharePointFileDownloader {
public static void main(String[] args) {
String sharePointSiteUrl = "https://your-sharepoint-site-url";
String fileUrl = "https://your-sharepoint-site-url/_api/web/getfilebyserverrelativeurl('/sites/your-site/folder/filename.docx')/$value";
try {
downloadFileFromSharePoint(sharePointSiteUrl, fileUrl, "downloaded_file.docx");
System.out.println("File downloaded successfully.");
} catch (IOException e) {
System.out.println("Error downloading file: " + e.getMessage());
}
}
public static void downloadFileFromSharePoint(String sharePointSiteUrl, String fileUrl, String outputFile) throws IOException {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(sharePointSiteUrl));
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("GET");
try (InputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
}
}
public static String getAccessToken(String sharePointSiteUrl) throws IOException {
// Replace this method with your code to get the access token from SharePoint using authentication method of your choice
return "your-access-token";
}
}
Make sure you replace the sharePointSiteUrl and fileUrl with the actual URLs of your SharePoint site and the file you want to download. Also, implement the getAccessToken method to retrieve the access token from SharePoint using your authentication method (e.g., OAuth, username-password authentication).
This code uses the SharePoint REST API to download the file and saves it to the specified outputFile. Please note that you will need to provide the appropriate authentication mechanism to access SharePoint and retrieve the access token.
You can run this Java code using any Java IDE or by executing it from the command line.