2017-05-04 36 views
-2

我是初學者,我想問一下如何通過POJO類讀取文本文件並從文件讀取器調用方法?我經歷了很多鏈接,但仍然沒有找到任何最佳解決方案。在此先感謝您的幫助。POJO類與文件讀取器

如何將POJO類,文件讀取器和文本文件一起使用?

+0

歡迎來到Stack Overflow!這個問題還不清楚。你想調用一個方法_from_ FileReader?或者你想調用FileReader類的方法嗎? –

+0

對不起,我想調用FileReader類的方法:) – Han

+0

[這些例子](https://www.mkyong.com/java/how-to-read-file-from-java- bufferedreader-example /)看起來OK。 –

回答

0

如果您想使用文本文件中的內容(如任何字符/完整內容)。您可以使用FileReader從文件讀取並存儲到POJO類變量中並在應用程序中的任何位置使用。

public class YourPOJOClass { 

private char firstChar; 
private String address; 

public void setFirstChar(char firstChar){ 
this.firstChar=firstChar; 
} 
public char getFirstChar(){ 
return firstChar; 
} 
public void setAddress(String address){ 
this.address=address; 
} 
public String getAddress(){ 
return address; 
} 

} 

::::::::file.txt::::::::: 

I Love India 

::::::::file.txt::::::::: 




public class Test{ 

public static void main(String[] args){ 

YourPOJOClass pojoClass=new YourPOJOClass(); 

File file=new File("C:\\file.txt"); 
FileReader reader=new FileReader(file); 

char[] contents=new char[20]; 
reader.read(contents); //Reding and Storing into contents char[] 

    pojoClass.setFirstChar(contents[0]); //Reading the first character and setting to Pojo class variable 'firstChar' 
    pojoClass.setAddress(String.valueOf(contents)); //Reading the first character and setting to Pojo class variable 'address' 

System.out.println(pojoClass.getFirstChar()); //Output: I 
System.out.println(pojoClass.getAddress()); // OutPut: I Love India 

} 

} 
+0

感謝您的幫助,我非常感謝。 – Han