java 讀取指定某一行的文字

guile發表於2019-02-27
// 讀取指定某一行的文字
public static String getCertainLineOfTxt(String filePath, int lineNumber){
	FileReader fr = null;
	LineNumberReader reader = null;
	String txt = "";

	try{
		File file = new File(filePath);
		fr = new FileReader(file);
		reader = new LineNumberReader(fr);

		int lines = 0;

		while(txt != null){
			lines ++;

			txt = reader.readLine(); // Read a line of text.

			if(lines == lineNumber){
				//System.out.println( "txt: " + txt + " lines = " + lines );
				return txt;
			}
		}

		return txt;
	}catch(Exception e){
		e.printStackTrace();

		return txt;
	}finally{
		try{
			reader.close();
		}catch(IOException e){
			e.printStackTrace();
		}

		try{
			fr.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}

呼叫

String txt = getCertainLineOfTxt("c:\test.txt", 10);

 

 

 

 

 

相關文章