如何使用Java程序连接GitHub并上传文件?
Hey Raju, let's walk through how to connect to GitHub using Java and upload files successfully. Here's a step-by-step guide with practical code examples:
Java连接GitHub并上传文件的实现指南
1. 准备工作:创建GitHub个人访问令牌(PAT)
Before writing any code, you'll need a secure way to authenticate with GitHub:
- Log into GitHub, go to Settings > Developer settings > Personal access tokens > Tokens (classic)
- Generate a new token, and make sure to check the
repopermission (this is required to upload files to both public and private repositories) - Save this token somewhere safe — don't share it with anyone, as it grants access to your GitHub repositories
2. 添加依赖(Maven为例)
We'll use the github-api library from kohsuke, which wraps GitHub's REST API and saves us from writing raw HTTP requests. Add this dependency to your pom.xml:
<dependency> <groupId>org.kohsuke</groupId> <artifactId>github-api</artifactId> <version>1.317</version> <!-- Use the latest stable version available --> </dependency>
3. 编写Java代码实现连接与文件上传
Here's a complete, commented example that handles authentication, connects to GitHub, and uploads a file to your target repository:
import org.kohsuke.github.*; import java.io.File; import java.io.IOException; public class GitHubFileUploader { public static void main(String[] args) { // Replace these values with your own String githubUsername = "your-github-username"; String repoName = "your-target-repo-name"; String personalAccessToken = "your-generated-pat"; String localFilePath = "/path/to/your/local/file.pdf"; // Path to the file you want to upload String repoTargetPath = "docs/uploaded-file.pdf"; // Where to place the file in the repo String commitMessage = "Upload file via Java application"; try { // 1. Connect and authenticate to GitHub GitHub github = new GitHubBuilder().withOAuthToken(personalAccessToken).build(); // Verify the connection (optional, but useful to confirm auth works) GHUser currentUser = github.getMyself(); System.out.println("Successfully connected to GitHub as: " + currentUser.getLogin()); // 2. Fetch the target repository GHRepository repo = github.getRepository(githubUsername + "/" + repoName); // 3. Upload the file File fileToUpload = new File(localFilePath); repo.createContent() .content(fileToUpload) .path(repoTargetPath) .message(commitMessage) .branch("main") // Replace with your target branch (e.g., master for older repos) .commit(); System.out.println("File uploaded successfully to GitHub!"); } catch (IOException e) { System.err.println("Something went wrong during the GitHub operation:"); e.printStackTrace(); } } }
Key code notes:
- Authentication: Using
withOAuthToken()is far safer than username/password auth, and lets you control exactly what permissions the app has - Repository access: The
getRepository()method uses the formatusername/repository-nameto target your repo - File upload: The
createContent()method chain handles all the heavy lifting — it even creates parent folders in the repo if they don't exist
4. Troubleshooting common issues
- Auth failures: Double-check your PAT is correct, hasn't expired, and has the
repopermission enabled - Repo not found: Ensure your username and repo name are spelled correctly, and that your account has write access to the repo
- File not found: Verify the local file path is correct and the file exists on your system
- Branch errors: Confirm your target branch exists (many repos use
maininstead ofmasternow)
内容的提问来源于stack exchange,提问作者Raju
相关产品推荐
相关产品推荐

