java文件

package test;

import java.io.*;

public class FileUtils {


    /**
     * @param message 保存的消息
     * @param contentFile 保存的文件
     * 将消息存储,一个文件保存保存消息的数据,一个保存消息的查找索引
     * @throws IOException
     */
    public static void saveDataLog(String message,File contentFile) throws IOException {
        String indexFilePath = "message-00000.index";
        File indexFile = new File(indexFilePath);

        BufferedWriter indexWriter = new BufferedWriter(new FileWriter(indexFile,true));
        BufferedWriter contentWriter = new BufferedWriter(new FileWriter(contentFile,true));

        Integer indexTotalLines = getTotalLines(indexFile);
        Integer contentTotalLines = getTotalLines(contentFile);
        String indexString = indexTotalLines +","+contentTotalLines+","+indexFilePath+"\n";

        indexWriter.write(indexString);
        contentWriter.write(message+"\n");

        indexWriter.close();
        contentWriter.close();
    }


    /**
     * @param number
     * @param file
     * 根据行数获取第几行的数据
     * @return
     * @throws IOException
     */
    public static String getNumLine(Integer number,File file) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        Integer count = 0;

        String line = null;
        while ((line = reader.readLine()) != null){
            if(number == count){
                break;
            }
            count += 1;
        }
        reader.close();
        return line;
    }

    /**
     * @param file
     * 获取文件的总行数
     * @return 文件总的行数
     * @throws IOException
     */
    public static Integer getTotalLines(File file) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        Integer count = 0;
        while (reader.readLine() != null){
            count += 1;
        }
        reader.close();
        return count;
    }

    /**
     * 
     * @param indexString
     * @return
     * @throws IOException
     */

    public static String[] getLineByIndex(String indexString) throws IOException {
        String[] splitArray = indexString.split(",");
        return splitArray;
    }

    public static void main(String[] args) throws IOException {

//        System.out.println(getTotalLines(new File("message.txt")));
//        System.out.println(getNumLine(2,new File("message.txt")));
//        saveDataLog("this is a sting.",new File("message.message"));

        String[] index = getLineByIndex("2,3");
        Integer lineByIndex = Integer.parseInt(index[1]);
        String numLine = getNumLine(lineByIndex, new File("message.message"));
        System.out.println(numLine);
    }

}

 

转载于:https://www.cnblogs.com/snow-wolf-1/p/11584944.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值