Struts2 Action读取web根目录上的文件夹Uploadfile内的文件

Struts2 Action读取web根目录下的文件夹Uploadfile内的文件

web根目录:109UPload 

 

109UPload

   
        |------Uploadfile    
        |           |------109.txt    
        |------WEB-INF    

 

Action类读取文件夹Uploadfile内的文件109.txt的方法有:

 

方法一:

public class SaveAction implements Action{

public static String getRootPath(){    
	
       //因为类名为"SaveAction",因此" SaveAction.class"一定能找到    
	
       String result = SaveAction.class.getResource("SaveAction.class").toString();    
	
       int index = result.indexOf("WEB-INF");  
	
       if(index == -1){    
	
           index = result.indexOf("bin");    
	
       }    
	
       result = result.substring(0,index);    
	
       if(result.startsWith("jar")){    
	
           // 当class文件在jar文件中时,返回"jar:file:/F:/ ..."样的路径     
	
           result = result.substring(10);    
	
       }else if(result.startsWith("file")){    
	
           // 当class文件在class文件中时,返回"file:/F:/ ..."样的路径     
	
           result = result.substring(6);    
	
       }    
	
       if(result.endsWith("/"))result = result.substring(0,result.length()-1);//不包含最后的"/"    
	
       return result;    
	
 }    
	
@Override
	
public String execute() throws Exception {	

File file = new File(getRootPath()+"/Uploadfile/109.txt");

FileReader fr = new FileReader(file);

BufferedReader bfr = new BufferedReader(fr);

//跳过第一行标题
String line = bfr.readLine();

while(true){

line = bfr.readLine();

//到达流末尾时,停止读取文件
 if(line == null)break;
  System.out.println(line);
}
}

 

方法二:

 

public class SaveAction implements Action{

	
public static String getRootPath(){    
	
private String inputPath;
	
public String getInputPath() {
	
return inputPath;
	
}

public void setInputPath(String inputPath) {
	
this.inputPath = inputPath;
	
}
	
@Override
	
public String execute() throws Exception {
	
String targetFile = ServletActionContext.getRequest()	
                                   .getRealPath(inputPath);
	
File file = new File(targetFile);
	
FileReader fr = new FileReader(file);
	
BufferedReader bfr = new BufferedReader(fr);
	
//跳过第一行标题
	
String line = bfr.readLine();
		
DateFormat df = new SimpleDateFormat ("yyyy-MM-dd HH:mm");
		
while(true){
	
line = bfr.readLine();
	
//到达流末尾时,停止读取文件
	
if(line == null)break;

System.out.println(line);
}
}
}

SaveAction 在struts.xml文件要配置一个参数,该参数被
ServletActionContext.getRequest().getRealPath(inputPath)读取:

<action name="save" class="action.SaveAction">	
<param name="inputPath">/UploadFile/109.txt</param>	
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>	
</action>