当前位置: 代码迷 >> Java Web开发 >> 诸位:jsp页面中怎样读取文件
  详细解决方案

诸位:jsp页面中怎样读取文件

热度:4295   发布时间:2013-02-25 21:14:53.0
各位:jsp页面中怎样读取文件
前提: eclipse,tomcat
工程名:Test
将要读取文件:Test/WebContent/test/tmp.txt

请问在jsp中怎样读取上面的tmp文件


最好给出一个例子,谢谢各位

------解决方案--------------------------------------------------------
此处省去87个字
------解决方案--------------------------------------------------------
找一本java教程从头到尾好好看看。
------解决方案--------------------------------------------------------
还真没想过这个.
服务层输入流读到字符串里,
存到request或者其他什么,
再从页面取

不知道有没有其他简便的方法.
------解决方案--------------------------------------------------------
不知这个是不是你所需求的,或许有些麻烦:
import java.io.*;
import java.net.*;

/**
 * 单线程连接
 * @author Administrator
 *
 */

public class RemoteFileClient {
protected BufferedReader socketReader;
protected PrintWriter socketWriter;
protected String hostIp;
protected int hostPort;

//客服端


public RemoteFileClient(String aHostIp, int aHostPort) {
hostIp = aHostIp;
hostPort = aHostPort;
}
public String getFile(String fileNameToGet) {
StringBuffer fileLines = new StringBuffer();

try {

//我们用 PrintWriter 把请求发送到主机,PrintWriter 是我们在创建连接期间建立的。

socketWriter.println(fileNameToGet);
socketWriter.flush();

String line = null;
while ((line = socketReader.readLine()) != null)
fileLines.append(line + "\n");
} catch (IOException e) {
System.out.println("Error reading from file: " + fileNameToGet);
}

return fileLines.toString();
}

public void setUpConnection() {
try {
Socket client = new Socket(hostIp, hostPort);

socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
socketWriter = new PrintWriter(client.getOutputStream()); // 我们把 Socket 的 InputStream 包装进 BufferedReader 以使我们能够读取流的行。然后,我们把 Socket 的 OutputStream 包装进 PrintWriter 以使我们能够发送文件请求到服务器

} catch (UnknownHostException e) {
System.out.println("Error setting up socket connection: unknown host at " + hostIp + ":" + hostPort);
} catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
}
}
public void tearDownConnection() {
try {
socketWriter.close();
socketReader.close();
} catch (IOException e) {
System.out.println("Error tearing down socket connection: " + e);
}
}
 


public static void main(String[] args) {
//服务端接受请求
RemoteFileClient server = new RemoteFileClient(3000);
server.acceptConnections();


//客服端请求
RemoteFileClient remoteFileClient = new RemoteFileClient("127.0.0.1", 3000); //客户机用 Socket 连接到服务器。服务器用 ServerSocket 在端口 3000 侦听。客户机请求服务器 请求上的文件内容
remoteFileClient.setUpConnection();


String fileContents = remoteFileClient.getFile("I://论坛/JSP与XML的结合.txt"); //从服务器和端口号倾听获取对应的具体文件

remoteFileClient.tearDownConnection();

System.out.println(fileContents);
}


//服务端

int listenPort;
public RemoteFileClient(int aListenPort) {
listenPort = aListenPort;
}
public void acceptConnections() {
try {
ServerSocket server = new ServerSocket(listenPort);
Socket incomingConnection = null;
while (true) {
  相关解决方案