Java实现TXT文件内容拆分:提取IP与端口至对应数组
Hey there! Let's tackle your two Java questions about handling TXT file content—first the general case of splitting content into an array, then your specific scenario of extracting IPs and ports into separate arrays.
一、通用方法:将TXT文件内容拆分至数组
The core idea here is to first read the entire content of the TXT file, then split it using a delimiter that matches your needs (like spaces, newlines, commas, etc.). Here's how you can do it:
Step-by-Step Breakdown
- Read the file: Use either modern Java APIs (Java 11+) for simplicity, or the classic
BufferedReaderfor compatibility with older versions. - Split the content: Use the
String.split()method with your target delimiter. Note that some delimiters (like dots or pipes) are regex special characters, so you'll need to escape them with a backslash. - Handle exceptions: File operations can throw
IOException, so make sure to wrap your code in a try-catch block or declare the exception in your method signature.
Example Code
Modern Approach (Java 11+)
import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class TxtToArray { public static void main(String[] args) { try { // Read all content from the file into a single string String fileContent = Files.readString(Paths.get("your-file.txt")); // Split by spaces (adjust the delimiter to match your needs, e.g., "\\n" for newlines) String[] contentArray = fileContent.split(" "); // Print the array elements for (String element : contentArray) { System.out.println(element); } } catch (IOException e) { e.printStackTrace(); } } }
Classic Approach (Pre-Java 11)
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TxtToArrayClassic { public static void main(String[] args) { StringBuilder contentBuilder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader("your-file.txt"))) { String line; while ((line = br.readLine()) != null) { contentBuilder.append(line).append(" "); // Append lines with space separator } String fileContent = contentBuilder.toString().trim(); String[] contentArray = fileContent.split(" "); // Print the array elements for (String element : contentArray) { System.out.println(element); } } catch (IOException e) { e.printStackTrace(); } } }
二、具体场景:提取IP与端口到对应数组
For your specific case where server.txt contains "192.168.1.2,80 192.168.1.3,3306", we'll need to:
- Read the file content
- Split the content into individual server entries (using space as the delimiter)
- For each entry, split into IP and port (using comma as the delimiter)
- Store IPs in
String[] ipserverand ports inString[] port - Print all elements of both arrays
Complete Example Code
import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class IpPortExtractor { public static void main(String[] args) { try { // Read the server.txt file content String serverContent = Files.readString(Paths.get("server.txt")).trim(); // Split into individual server entries (split by spaces) String[] serverEntries = serverContent.split(" "); // Initialize arrays to hold IPs and ports (size matches number of server entries) String[] ipserver = new String[serverEntries.length]; String[] port = new String[serverEntries.length]; // Iterate over each entry to extract IP and port for (int i = 0; i < serverEntries.length; i++) { String[] ipPortPair = serverEntries[i].split(","); ipserver[i] = ipPortPair[0]; port[i] = ipPortPair[1]; } // Print the IP array System.out.println("IP Addresses:"); for (String ip : ipserver) { System.out.println("- " + ip); } // Print the Port array System.out.println("\nPorts:"); for (String p : port) { System.out.println("- " + p); } } catch (IOException e) { System.err.println("Error reading the file: " + e.getMessage()); e.printStackTrace(); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Invalid format in server.txt: Each entry should be in 'IP,PORT' format"); e.printStackTrace(); } } }
What This Code Does
- Reads the
server.txtcontent in one go (Java 11+ API) - Splits the content into two server entries:
"192.168.1.2,80"and"192.168.1.3,3306" - For each entry, splits on the comma to get the IP and port, then stores them in the respective arrays
- Adds error handling for file reading issues and invalid format (in case an entry doesn't have a comma)
- Prints out all IPs and ports in a readable format
When you run this code, the output will be:
IP Addresses: - 192.168.1.2 - 192.168.1.3 Ports: - 80 - 3306
内容的提问来源于stack exchange,提问作者Jordi
相关产品推荐
相关产品推荐

