import java.io.*;
public class TextProcessing {
// Text Processing
public static void main(String[] args) throws IOException {
String filePath = "1.txt" ;
File[] fileInputListsPath = new File("TxtDocument\\2512").listFiles();
String fileOutputPath = "TxtDocument\\4.txt";
createFile(filePath);
writeFileAppend(filePath, "content1");
writeFileOverlay(filePath, "over");
if(fileInputListsPath != null) {
fileCombine(fileInputListsPath, fileOutputPath);
}
readFile(filePath);
}
/**
* 功能描述:创建文件
* @param filePath
*/
public static void createFile(String filePath) {
try {
File file = new File(filePath);
if(!file.exists())
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 功能描述:文本追加写入
* @param filePath
* @param Content
*/
public static void writeFileAppend(String filePath, String Content) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter(filePath, true);
fileWriter.write(Content);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 功能描述:文本覆盖写入
* @param filePath
* @param Content
*/
public static void writeFileOverlay(String filePath, String Content) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(filePath);
printWriter.write(Content);
printWriter.flush();
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 功能描述:文件文本读取
* @param filePath
*/
public static void readFile(String filePath) {
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
try {
File file = new File(filePath);
inputStreamReader = new InputStreamReader(new FileInputStream(file), "gbk");
bufferedReader = new BufferedReader(inputStreamReader);
String string;
while((string = bufferedReader.readLine()) != null) {
System.out.println(string);
}
bufferedReader.close();
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 功能描述:txt文件合并
* @param fileInputListsPath
* @param fileOutputPath
* @throws IOException
*/
public static void fileCombine(File[] fileInputListsPath, String fileOutputPath) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileOutputPath));
int fileCount = 0, folderCount = 0;
for(File file : fileInputListsPath) {
if(file.isFile()) {
fileCount += 1;
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
} else {
folderCount += 1;
}
}
bufferedWriter.close();
System.out.println(fileCount);
System.out.println(folderCount);
}
}
Java | 文本处理
最新推荐文章于 2024-06-22 22:45:21 发布