不冷博客

使用Java简单处理文件(获取文件每行信息)

前言

因为百度的收录提交需要用到网站链接,而提交方式选的用Java提交
总的来说就是要把文件内每行的链接都变成带这个双引号的和逗号————"地址",
用到的Java中的文件操作,这里记录一下代码供大家学习交流

代码

package com.jike.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class ChangeFile {

    public static String[] read(String path) {
        // TODO Auto-generated method stub
        File file = new File(path);
        List list = new ArrayList();
        String[] nums = null;
        try {
            BufferedReader bw = new BufferedReader(new FileReader(file));
            String line = null;
            //因为不知道有几行数据,所以先存入list集合中
            while((line = bw.readLine()) != null){
                list.add(line);
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //确定数组长度
        nums = new String[list.size()];
        for(int i=0;i<list.size();i++){
            String s = (String)list.get(i);
            nums[i] = s;
        }
        return nums;
    }
    public static void main(String[] args) {
        String path = "D:/SEO软件/Sitemap/3/www.buleng.xyz/20210124175928195/a.txt";//文件路径
        String[] nums = read(path);
        
        try {
            FileOutputStream fop = new FileOutputStream(path);//文件输出流这里会自动创建文件
            OutputStreamWriter osw = new OutputStreamWriter(fop, "UTF-8");
            BufferedWriter bw2 = new BufferedWriter(osw);//带有缓冲区的reader
            String sb = "";
            for(int i=0;i<nums.length;i++){
                System.out.println(nums[i]);
                nums[i] = '"'+nums[i]+'"'+',';
                sb+=nums[i]+"\n";
            }
            System.out.println(sb);
            bw2.write(sb.toString());
            
            //关闭资源
            bw2.close();
            osw.close();
            fop.close();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »