Two common methods for Java to read and store files

Java reads files, the method on the Internet has been explained very comprehensively, so I won't introduce it here.
This article mainly introduces how to store the data in the file into the data type you want. If you want to store it as an array of strings, you need to define the size of the array, so you must first obtain the total number of lines in the file; and using generic classes to store data saves this step and is more flexible and convenient to use.

1. String array (String[])

		String file = "1.txt";		
		int fileLength = 0;		
		try {
    
    
			// 获取要读取文件的总行数
			fileLength = (int) Files.lines(Paths.get(file)).count();	
			System.out.println(fileLength);
		} catch (IOException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
		// 获取文件内容,字符串数组定义必须定义数组大小,所以需要先计算出fileLength的值
		String[]data = new String[fileLength];
		String temp = "";
		int i=0;
		try {
    
    
			FileInputStream fileInputStream = new FileInputStream(file);
			BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
			while((temp = reader.readLine())!=null) {
    
    
				data[i++] = temp;	// 使用数组存储				
			}
		}catch(Exception e) {
    
     
			e.printStackTrace();
		}
		
		// 输出
		for(int j=0;j<data.length;j++) {
    
    
			System.out.println(data[j]);
		}

2. Generic class (ArrayList<String>)

		String file = "1.txt";
		// 这里的arrayList存储的数据类型是String,不需要定义arrayList的大小,使用比较灵活
		ArrayList<String>arrayList = new ArrayList<>();
        String temp = "";
        try {
    
    
            FileInputStream fis = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            while((temp = reader.readLine())!=null) {
    
    
                arrayList.add(temp);	// 使用泛型类存储
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        // ArrayList-->String[](我们需要的结果类型是字符串数组,所以这里进行转换)
        String[]data = arrayList.toArray(new String[arrayList.size()]);
        
        // 输出
        for(int j=0;j<data.length;j++) {
    
    
			System.out.println(data[j]);
		}

Sometimes, we can process a row of data while reading it, then using an array or a generic can achieve the goal, and there is no need to convert the generic to an array.

Guess you like

Origin blog.csdn.net/qq_34205684/article/details/109381585