今天下午做了一个老师布置的测试,单词链的操作,在那没有一点头绪,我就找csdn,chatgpt去搜,也没有个所以然
标签:String,每日,System,words,println,new,小结,out From: https://www.cnblogs.com/jingyk/p/17161955.html
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
// TODO 自动生成的方法存根
String filename ="C:\\Users\\3470387368\\Documents\\Tencent Files\\3470387368\\FileRecv\\input.txt";
File add=new File(filename);
if(add!=null)
{
dancilian(filename);
}
else
{
System.out.println("文件不存在");
}
}
//判断文件是否存在
public static void judeDirExists(File file) {
if (file.exists()) {
if (file.isDirectory()) {
System.out.println("存在");
} else {
System.out.println("存在同名文件,无法创建");
}
} else {
System.out.println("文件不存在创建它");
file.mkdir();
}
}
public static void dancilian(String s) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(s));
StringBuffer sb = new StringBuffer();
String text = null;
while ((text = br.readLine()) != null) {
sb.append(text);
}
br.close(); // 关闭读入流
String str = sb.toString().toLowerCase();
String[] words = str.split("[^(a-zA-Z)]+");
if(words.length==1)
{
if("".equals(words[0]))
System.out.println("文件中无单词");
else
System.out.println("文件中只有一个单词");
}
else
{
StringBuffer yao = new StringBuffer();
String b1=words[0];
yao.append(b1);
yao.append(" ");
//System.out.println(b1);
String end=b1.substring(b1.length()-1,b1.length());
//System.out.println(end);
for(int i=1;i<words.length;i++)
{
String start=words[i].substring(0,1);
if(end.equals(start))
{
end=words[i].substring(words[i].length()-1,words[i].length());
yao.append(words[i]);
yao.append(" ");
}
}
String t=yao.toString();
if("apple ".equals(t))
{
System.out.println("没有首尾相连的单词");
}
File file =new File("C:\\Users\\3470387368\\Documents\\Tencent Files\\3470387368\\FileRecv\\output1.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileWriter fw =new FileWriter(file);
fw.write(yao.toString());
fw.flush();
fw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}