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);
}
}