我正在尝试逐行保存文件作为字符串数组,但我是初学者并且很困惑。
package com.java24hours;
import java.io.*;
public class ShorteningVelocity {
public static void main(String[] arguments) throws IOException {
FileReader SVfile = new FileReader(new File("C:\\Documents\\10-27-15110mMKPSS3.dat"));
BufferedReader br = new BufferedReader(SVfile);
String temp = br.readLine();
while (temp != null) {
temp = br.readLine(); //reads file line by line
System.out.println();
}
}
}
答案 0 :(得分:2)
Java Arrays的大小不能增长,所以你使用一个列表(来自java.util)。列表会动态增长,因此您可以根据需要随时使用add()
。由于列表可能包含所有内容,因此您可以使用List<TypeOfWhatYouWantToStore>
指定要包含的内容。因此,List类被称为泛型类。
将它转换为数组(因为这是你想要的)有点奇怪。您使用列表的大小分配数组,然后在列表中使用toArray
。这将返回列表,转换为数组。它必须将数组作为参数,因为编译器在使用泛型编译时需要它。
package com.java24hours;
import java.io.*;
import java.util.*;
public class ShorteningVelocity {
public static void main(String[] arguments) throws IOException {
FileReader SVfile = new FileReader(new File("C:\\Documents\\10-27-15110mMKPSS3.dat"));
BufferedReader br = new BufferedReader(SVfile);
String temp = br.readLine();
List<String> tmpList = new ArrayList<>();
while (temp != null) {
tmpList.add(temp);
temp = br.readLine(); //reads file line by line
}
String[] myArray = new String[tmpList.size()];
myArray = tmpList.toArray(myArray);
}
}
编辑:使用Files.readAllLines()
(请参阅有关您问题的评论)更容易且可能更快,但使用此循环,您可以看到更多正在发生的事情。< / p>
编辑2:更常见的是使用此循环:
String temp;
List<String> tmpList = new ArrayList<>();
while ((temp = br.readLine()) != null) {
tmpList.add(temp);
}
循环现在正在执行以下操作:
br.readLine()
读入temp
temp
为空,请退出循环temp
不为空,请将其添加到列表您也可以通过执行以下操作来打印数组:
for (String str : myArray) {
System.out.println(str);
}
答案 1 :(得分:0)
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("C:\\Documents\\10-27-15110mMKPSS3-out.dat");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
FileReader SVfile = new FileReader(new File("C:\\Documents\\10-27-15110mMKPSS3.dat"));
BufferedReader br = new BufferedReader(SVfile);
String temp;
while ((temp = br.readLine()) != null) {
//reads file line by line
System.out.println();
outFile.println(temp);
}
outFile.close();
} catch (IOException e) {
}
}
答案 2 :(得分:0)
public static void main(String[] args){
List<String> tmpList = new ArrayList<>();
try {
FileReader fileReader = new FileReader(new File("D:\\input.txt"));
BufferedReader bufferedReader = new BufferedReader(fileReader);
String temp;
while ((temp = bufferedReader.readLine()) != null) {
tmpList.add(temp);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] myArray = new String[tmpList.size()];
myArray = tmpList.toArray(myArray);
for(int i = 0; i< myArray.length ; i ++){
System.out.println(myArray[i]);
}