[英]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.