在Java中将文本文件中的数据保存到数组中
我得到了这份调查结果的文本文件: 我已经设法让Java读取它,并使用以下代码显示它:在Java中将文本文件中的数据保存到数组中,java,arrays,Java,Arrays,我得到了这份调查结果的文本文件: 我已经设法让Java读取它,并使用以下代码显示它: import java.io.*; class Final { public static void main (String [] args) throws Exception { File file = new File ("C:\\Users\\loren\\Desktop\\t\\respuestas.txt"); BufferedReader br = new
import java.io.*;
class Final {
public static void main (String [] args) throws Exception {
File file = new File ("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) !=null)
System.out.println(st);
}
}
但我不知道如何将其保存在2D阵列上,有人有任何可能的解决方案吗?1-使用此类逐行读取文件数据
import java.io.*;
public class FileReader {
private String fileName, fileContent = null, line;
public FileReader(String f) {
fileName = f;
reader();
}
private void reader() {
try {
fileContent = "";
// FileReader reads text files in the default encoding
Reader fileReader = new java.io.FileReader(fileName);
// Wrapping FileReader in BufferedReader
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
fileContent += line;
fileContent += '\n';
}
// Closing the file
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
}
/**
* Get content of file
*
* @return String
*/
public String getFileContent() {
return fileContent;
}
}
在行上进行2次循环,并将它们添加到数组的特定索引中!您需要一个函数,该函数跳过每行中的空格,只提取值。使用字符串数组列表,然后将该列表转换为二维字符串数组。
在这种情况下,“结果”将是您想要的输出。
假设:输入文件中的单词由制表符分隔
import java.io.*;
import java.util.List;
import java.util.ArrayList;
class Final {
public static void main (String [] args) throws Exception {
File file = new File ("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
List<String[]> resultList = new ArrayList<>();
while ((st=br.readLine()) !=null) {
resultList.add(st.split("\t"));
}
String[][] result = new String[resultList.size()][resultList.get(0).length];
for(int i=0; i<resultList.size(); i++) {
result[i] = resultList.get(i);
}
}
}
import java.io.*;
导入java.util.List;
导入java.util.ArrayList;
期末考试{
公共静态void main(字符串[]args)引发异常{
File File=新文件(“C:\\Users\\loren\\Desktop\\t\\respuestas.txt”);
BufferedReader br=新的BufferedReader(新文件读取器(文件));
字符串st;
List resultList=new ArrayList();
而((st=br.readLine())!=null){
结果列表.add(st.split(“\t”);
}
字符串[][]结果=新字符串[resultList.size()][resultList.get(0.length)];
对于(int i=0;i有很多方法可以做到这一点。为了有效地将文件内容放置到二维(2D)中数组中,你需要知道你的数组需要多大,以便适当地把所有的东西都放进去,这样当你填充数组时,就不会碰到生成<强> ARAYOUTOFFUNCTIONEX/<强>的问题。数组的大小需要先建立,然后再把元素放入其中。要考虑的事情是:
- 这是正确的文本文件开始吗
- 文件中有多少有效数据行
- 每行有多少列
- 文件中是否有不需要的行(如标题行)
还是空白行)
这就是为什么使用诸如ArrayList、Map、HashMap等收集机制是解决此问题的好方法。在检索完数据后,您始终可以将该收集转换为数组
通过查看您的示例文件(嗯……它的图像:/)看起来有一个标题行简要描述了每个文件行中的每个数据列的用途。您没有指定是否要将其作为二维数组的一部分。您也没有指定二维数组的数据类型,它是对象、字符串还是整数
考虑到上述情况,我们必须假设您不希望将标题行放入数组中,而只希望每个行列中包含原始整数数据值。这就回答了数组数据类型问题…integer(int)
以下是执行任务的一种方法:
public int[][] readDataFile(String filePath) throws FileNotFoundException {
ArrayList<int[]> list;
// Try with resources...Auto closes scanner
try (Scanner sRead = new Scanner(new File(filePath))) {
list = new ArrayList<>();
String line;
int lineCounter = 0;
while (sRead.hasNextLine()) {
line = sRead.nextLine().trim();
// Skip any blank lines
if (line.equals("")) { continue; }
lineCounter++;
// Is it a valid data file?
if (lineCounter == 1 && !line.startsWith("P1")) {
// No it's not!
JOptionPane.showMessageDialog(null, "Invalid Data File!",
"Invalid File!",
JOptionPane.WARNING_MESSAGE);
return null;
}
// Skip the Header Line
else if (line.startsWith("P1")) { continue; }
// Split the incomming line and convert the
// string values to int's
String[] strArray = line.split("\\s+");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
// Add to ArrayList
list.add(intArray);
}
}
// Convert the ArrayList to a 2D int Array
int[][] array = new int[list.size()][list.get(0).length];
for (int i = 0; i < list.size(); i++) {
System.arraycopy(list.get(i), 0, array[i], 0, list.get(i).length);
}
return array;
}
请看旁边的内容,你介意将文件粘贴到帖子中吗?这样我们可以复制/粘贴它,看看你使用的是什么类型的空白等等。(1-如何将其保存在二维数组上
-首先,我不知道这意味着什么。如果你有一行数据,为什么需要二维数组。2)您不知道文件的大小,数组的大小是硬编码的,因此不要使用数组。而是使用将根据需要增长的ArrayList
。
try {
int[][] a = readDataFile("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
for (int[] a1 : a) {
System.out.println(Arrays.toString(a1));
}
} catch (FileNotFoundException ex) { ex.printStackTrace(); }