[英]Reading String IP addresses to store in 2D string array
我有一個帶有IP地址集的文本文件,我用BufferedReader讀取了該文件,希望將其存儲在2D字符串數組中。
這是我的文本文件:
102.168.212.226, 104.170.214.228, 0 57.68.58.212, 59.70.60.214, 1 10.42.12.22, 12.44.14.24, 2 78.16.22.234, 80.18.24.236, 3 123.168.2.2, 125.170.4.4, 4
這是我的代碼:
import java.io.;
import java.util.;
public class IPAddressLookup
{
IPAddressLookup() //Constructor
{
int Width = 0, Height = 0;
try
{
File fileA = new File("ClassA.txt");
BufferedReader bra = new BufferedReader(new FileReader(fileA));
String line = "";
String[] str;
while((line = bra.readLine()) != null )
{
str = line.trim().split(", ");
Width = str.length;
Height++;
}
String [][] ClassATable = new String[Height][Width];
for(int i = 0; i < Height; i++)
{
if((line = bra.readLine()) != null )
{
str = line.trim().split(", ");
for(int j = 0; j < Width; j++)
ClassATable[i][j] = str[j];
}
}
for(int i = 0; i < Height; i++)
for(int j = 0; j < Width; j++)
System.out.println(ClassATable[i][j]);
System.out.println("The text file contains:");
System.out.println("Row : " +Height);
System.out.println("Column : " +Width);
}
catch(IOException e)
{
System.out.println("Error: File not found.");
}
}
public static void main(String args[])
{
IPAddressLookup acnl1 = new IPAddressLookup();
}
}
問題是當我嘗試打印String數組時,它在輸出中顯示“ null”。 還有什么方法可以從文件中讀取字符串IP地址並將它們存儲在整數2D數組中?
我對Java有點陌生。 誰能幫我這個 ?
似乎您正在讀取文件兩次,但是您沒有在重置閱讀器,因此在第二個循環中,您將從頂部重新開始。
您需要在循環之間添加類似以下內容: bra.getChannel().position(0)
(之后: String [][] ClassATable = new String[Height][Width];
)。 這將重置您的閱讀器,使其可以從頂部再次啟動。
試試這個代碼:
public class IPAddressLookup {
ArrayList<String[]> ip = new ArrayList<>();
IPAddressLookup() //Constructor
{
int Width = 0, Height = 0;
try
{
File fileA = new File("ClassA.txt");
BufferedReader bra = new BufferedReader(new FileReader(fileA));
String line = "";
String[] str;
while((line = bra.readLine()) != null )
{
str = line.trim().split(", ");
ip.add(str);
Width = str.length;
Height++;
}
String [][] ClassATable = new String[Height][Width];
for(int i=0 ; i<ip.size();i++){
String[] temp = ip.get(i);
for(int j=0;j<temp.length;j++){
ClassATable[i][j] = temp[j];
}
}
for(int i = 0; i < Height; i++)
for(int j = 0; j < Width; j++)
System.out.println(ClassATable[i][j]);
System.out.println("The text file contains:");
System.out.println("Row : " +Height);
System.out.println("Column : " +Width);
}
catch(IOException e)
{
System.out.println("Error: File not found.");
}
}
public static void main(String args[])
{
IPAddressLookup acnl1 = new IPAddressLookup();
}
}
結果:
102.168.212.226 104.170.214.228 0 57.68.58.212 59.70.60.214 1 10.42.12.22 12.44.14.24 2 78.16.22.234 80.18.24.236 3 123.168.2.2 125.170.4.4 4 The text file contains: Row : 5 Column : 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.