[英]reading from .txt file into a 2d array
我的txt文件全部用空格隔开,我知道如何读取文件,但不知道如何将数据放入数组
这是代码:
public static void main(String[] args) throws IOException
{
ArrayList<String> list=new ArrayList<>();
try{
File f = new File("C:\\Users\\Dash\\Desktop\\itemsset.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
String array[][] = null ;
try {
while ((line = br.readLine()) != null) {
}
br.close();
fr.close();
}
catch (IOException exception) {
System.out.println("Erreur lors de la lecture :"+exception.getMessage());
}
}
catch (FileNotFoundException exception){
System.out.println("Le fichier n'a pas été trouvé");
}
}
说明如下:
我的txt文件全部用空格隔开
读取每一行,并用空格将其分隔。 首先,您可以使用user.home
系统属性和相对路径来构造文件路径。 就像是,
File desktop = new File(System.getProperty("user.home"), "Desktop");
File f = new File(desktop, "itemsset.txt");
然后使用try-with-resources
并将每一行读入List<String[]>
List<String[]> al = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String line;
while ((line = br.readLine()) != null) {
al.add(line.split("\\s+"));
}
} catch (IOException exception) {
System.out.println("Exception: " + exception.getMessage());
exception.printStackTrace();
}
然后,您可以将List<String[]>
转换为String[][]
并使用Arrays.deepToString(Object[])
例如
String[][] array = al.toArray(new String[][] {});
System.out.println(Arrays.deepToString(array));
我只是被Java 8的美丽和它的Streams所迷住。
Path p = Paths.get(System.getProperty("user.home"),"Desktop","itemsset.txt");
String [][] twoDee = Files.lines(p)
.map((line)->line.trim().split("\\s+"))
.toArray(String[][]::new);
System.out.println(Arrays.deepToString(twoDee));
发现类似情况:
String []
int []
转换为int []
的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.