我有一个带有一组IP地址的文本文件,我用BufferedReader读取它想将它存储在一个二维字符串数组中。
这是我的文字档案:
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数组时,它显示&#34; null&#34;在输出中。 还有什么方法可以从文件中读取字符串IP地址并将它们存储在整数2D数组中吗?
我在Java方面有点新鲜。 任何人都可以帮我这个吗?
答案 0 :(得分:4)
您似乎正在阅读该文件两次,但您没有重置阅读器,因此在第二个循环中,您将从顶部重新开始。
您需要在循环之间添加如下内容:LastRow1 =.Cells(Rows.Count, 1).End(xlUp).Row
Cells(lastRow1 + 1, 1).Value = "Your value here"
LastRow2 =.Cells(Rows.Count, 2).End(xlUp).Row
Range("A" & LastRow1 & ".AutoFill Destination:=Range("A" & LastRow1 & ":A" & LastRow2 & "), Type:=xlFillDefault
(在此之后:bra.getChannel().position(0)
)。这将重置您的阅读器,以便它可以从顶部再次启动。
答案 1 :(得分:1)
试试这段代码:
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