JAVA 读取CSV文件

/**
 * @author uiao
 * @Title: TestCsv
 * @date 2018/8/717:00
 */
public class TestCsv {
    public static void main(String[] args) {
        TestCsv test = new TestCsv();
        test.test(3, 1);
    }
 
    public void test(int row, int col) {
        try {
            //先FileReader把文件读出来再bufferReader按行读  reader.readLine(); 没有标题用不着了
            BufferedReader reader = new BufferedReader(new FileReader("F:\\lianxi3.csv"));
            String line = null;
            int index = 0;
            while ((line = reader.readLine()) != null) {
                String item[] = line.split(",");//一行数组
                if (index == row - 1) {//?
                    if (item.length >= col - 1) {
                        String last = item[col - 1];//这里
                        System.out.println(last);
                    }
                }
                index++;
            }
        } catch (Exception e) {
            //在命令行打印异常信息在程序中出错的位置及原因。
            e.printStackTrace();
        }
    }
}
/**
 * @author uiao
 * @Title: 读取csv文件到一个数组
 * @date 2018/8/717:05
 */
public class HandleCsv {
    static String[] item = {};
 
    @SuppressWarnings("resource")
    public static String[] Handle() {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("E:\\sights.csv"));
            String line;
            while ((line = reader.readLine()) != null) {
                String info[] = line.split(",");
                int iteml = item.length;
                int infol = info.length;
                item = Arrays.copyOf(item, iteml + infol);//填充
                System.arraycopy(info, 0, item, iteml, infol);//组合数组
            }
        } catch (FileNotFoundException ex) {
            System.out.println("没找到文件!");
        } catch (IOException ex) {
            System.out.println("读写文件出错!");
        }
        System.out.println(Arrays.toString(item));
        return item;
    }

猜你喜欢

转载自blog.csdn.net/DreamWeaver_zhou/article/details/87877436