我有一个带有一组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