计算最长英语单词链

实验要求:

统一输入文件名称:input1.txt, input2.txt

统一输出文件名称:output1.txt,output2.txt

程序需要考虑下列异常状况: 例如,文件不存在,你的程序会崩溃么,还是能优雅地退出并给用户提示信息?

如果文件没有任何单词、只有一个单词、没有可以首尾相连的单词,程序应该如何输出?

如果输入文件有一万个单词,你的程序能多快输出结果?

设计思想:

首先对这个任务,进行划分,任务可分为:

(1)从文件中读取

(2)将结果输出到文件中

(3)编写查找方法

(4)根据后续的需要,我又做了一个文件的异常处理的方法,对文件位置不存在等情况进行处理。

package t2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class Longest {

	public static void main(String[] args) throws IOException {
		// TODO 自动生成的方法存根
		String str = readTxtFile("d:\文件\input.txt");
		if (str == null) {
			System.out.println("文件内容获取失败");
		}else
		{
			String result = StatList1(str);
			System.out.println(result);
			daochu(result);
		}
		

	}
	
	
	
	public static String readTxtFile(String filePath){ 
		try { 
			String encoding="GBK"; 
			File file=new File(filePath); 
			if(file.isFile() && file.exists()){ //判断文件是否存在 
			InputStreamReader read = new InputStreamReader( 
			new FileInputStream(file),encoding);//考虑到编码格式 
			BufferedReader bufferedReader = new BufferedReader(read); 
			String lineTxt = null;
			String lineText="";
			while((lineTxt = bufferedReader.readLine()) != null)
				{ 
				lineText+=(lineTxt); 
				} 
			read.close(); 
			return lineText;
			}
			else
				{ 
				System.out.println("找不到指定的文件"); 
				} 
			} catch (Exception e) { 
			System.out.println("读取文件内容出错"); 
			e.printStackTrace(); 
			} 
			return null;
		} 
	
	public static String StatList1(String str) {
		StringBuffer sb = new StringBuffer();
		//HashMap<String ,Integer> has = new HashMap<String ,Integer> (); // 打开一个哈希表
		String result = "";
		
		String[] slist = str.split("[^a-zA-Z]+");
		int n= 1;
		if (str == "") {
			System.out.println("文件中没有单词");
		}else if (slist.length == 1) {
			System.out.println("文件中只有一个单词");
		}else {
			
		
		
		//String[] n = new String[100];
		char[] shou = new char[slist.length + 100];
		char[] wei = new char[slist.length +100];
		System.out.println("一共有"+slist.length);
		for(int i = 0 ; i < slist.length ; i++)
		{
			if (slist[i] != null) {
				int length = slist[i].length();
			shou[i] = slist[i].charAt(0);
			wei[i] = slist[i].charAt(length-1);
			}
			
		}
		for(int j = 0 ; j < shou.length; j++)
		{
			if (wei[n] == shou[j]) {
				n = j;
				result += slist[j] + " ";
			}
		}
	
		
		
		    if (result == "") {
				System.out.println("没有收尾相连");
			}}
		     return result;
		
		}
	
	
	
	public static void daochu(String a) throws IOException
	{
		File file=new File("d:\文件\output.txt");
		FileOutputStream fos=new FileOutputStream(file);
		OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
		osw.append(a);
		osw.close();
		fos.close();
	}

}