java - 数组在写入后不保留其值
问题描述
我正在尝试将文件读入数组,每一行都将存储在数组的索引中。给定 text.txt 文件中的以下输入:
6afe
5af
3eafe
7fae
3sfs
1eef
我读入了数组,然后在控制台中打印出数组进行检查,但不知何故,数组在循环后没有保留它的值。我得到的输出是空的,之前和之后,但不在循环中间。请告诉我为什么 ?谢谢这是我得到的输出
nullline 0
nullline four
6afe
5af
3eafe
7fae
3sfs
1eef
nullline three
nullline four
我期望得到的输出是:
nullline 0 // array still empty here, i get it
nullline four // array still empty
6afe
5af
3eafe
7fae
3sfs
1eef
7fae // where here are null three ? in the actual ouput
3sfs // null three ?
这是我的代码:
import java.io.*;
public class readSortWrite
{
public static void main(String[] args) throws java.io.IOException
{
//input file
// to count lineNum
FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(fr);
//to read into array names[]
FileReader fr1 = new FileReader("text.txt");
BufferedReader br1 = new BufferedReader(fr1);
// output file
FileWriter fw = new FileWriter("sorted.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
// counting number of line
int lineNum = 0;
String line;
line = br.readLine();
while(line != null)
{
lineNum++;
line = br.readLine();
}
pw.close();
// System.out.println(lineNum + "lines");
// create an array of of lineNum size and write each line of file into array
String[] names = new String[lineNum];
String str;
str = br1.readLine();
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
// fr1.close();
System.out.println(names[3]+ " line three");
System.out.println(names[4] + " line four");
}
}
解决方案
前两行是null
因为您创建数组并在初始化它们之前打印值0
和4
索引,就像这样
String[] names = new String[lineNum];
String str;
str = br1.readLine();
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
对于倒数第二行,while
循环将读取buffer
直到它为空但没有任何循环迭代for
,因此仅填充names[0]
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
将其更改为类似
int i =0;
while (str!= null && i < lineNum) {
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
推荐阅读
- angular - 为什么我的 Angular 应用程序在 StackBlitz 上运行时会出错?
- php - 将表格导出到excel时如何使用utf-8
- python - sumy LexRankSummarizer() 输出文本的正确格式
- java - Hibernate 实体架构 @Table(schema="
"),获取表未找到异常 - html - 如何通过 Django 将 Html 代码保存在数据库中
- react-native - React Native fetch 在另一个 fetch 回调中不起作用
- excel - VBA code not working in Excel with dataset
- c# - 可以使用的 WPF DispatchTimers 的数量是否有限制
- angular - 通过单击显示以前的卡片并单击卡片并在角度 6 中隐藏其他索引
- java - 如何在 java 中修改 ipv6 的 NS/NA 消息?