如何使用 for 循环遍历 txt 文件中的行 Java

How to use a for-loop to go through the lines in a txt file Java

基本上我想做的是在 java 中制作一些东西,将向网站发送 POST 请求,但每次使用不同的令牌。我有一个名为 tokens.txt 的充满这些“令牌”的文件,我希望它针对每个请求循环遍历这些“令牌”,以便它为每个令牌发送一个请求。我过去在 python:

做过类似的事情
link = "https://example.com"
joined = 0
failed = 0
with open("tokens.txt", "r") as f:
    tokens = f.read().splitlines()
    for token in tokens:
        headers = {"Content-Type": "application/json", 
                   "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
                   "Authorization" : token}

        response = post(link, headers=headers).status_code
        if response > 199 and response < 300:
            joined += 1

        else:
            failed += 1

如您在 python 代码中所见,它循环遍历文件以更改令牌变量并发送请求

但是,我对 java 还很陌生,所以我不知道自己在做什么,我很困惑。

既然你想使用 for-loop 试试这个:

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        int joined = 0, failed = 0;

        try {

            URL url = new URL("https://example.com");
            Path path = Paths.get("tokens.txt");
            List<String> tokens = Files.readAllLines(path, StandardCharsets.UTF_8);

            for (String token : tokens) {
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11");
                connection.setRequestProperty("Authorization", token);

                int response = connection.getResponseCode();

                if (response > 199 && response < 300)
                    joined++;
                else
                    failed++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}