步骤
- 判断文本文件编码(避免乱码)
- 读取文本文件
- 写入
判断文本文件编码
public static void main(String[] args) throws IOException {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream("D:\\hanlp\\情感分析\\正向\\pos60000.txt"));
int p = (bin.read() << 8) +bin.read();
String code = null;
switch (p) {
case 0xefbb:
code = "UTF-8";
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
default:
code = "GBK";
}
System.out.println(code);
}
读取文本文件
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\hanlp\\情感分析\\正向\\pos60000.txt"),"GBK");
BufferedReader br = new BufferedReader(isr);
String temp = null;
while((temp = br.readLine()) != null){
System.out.println(temp);
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
读取加写入
public static void main(String[] args) throws IOException {
FileWriter fwriter = null;
String fileRootPath = "D:\\hanlp\\情感分析\\负向\\";
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\hanlp\\情感分析\\负向\\neg60000.txt"),"GBK");
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String temp = null;
int i=1;
while((temp = br.readLine()) != null){
String filePath = fileRootPath+i+".txt";
i++;
try {
fwriter = new FileWriter(filePath);
fwriter.write(temp);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fwriter.flush();
fwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
看完有用请点赞!!
咱不白嫖哈!
参考:https://www.iteye.com/blog/herestay-1782903
参考:https://www.cnblogs.com/qyy1207/p/10255363.html