我想在一个JSP页面中访问一个读取一个位于服务器上的.txt文件,这个文件的路径应该怎么样设置?
如果要访问别的机器的文件 就得需要别的机器把此文件服务开放
所以假如你要访问 B电脑的 xxtxt
就需要在B电脑架设web服务器 比如tomcat
然后 你可以用 xmlhttp访问B电脑的
http://b/xxtxt 来进行操作
File类有两个常用方法可以得到文件路径一个是:getCanonicalPath(),另一个是:getAbsolutePath(),可以通过File类的实例调用这两个方法例如filegetAbsolutePath()其中file是File的实例对象。下面是一个具体例子:
public class PathTest{
public static void main(String[] args)
{
File file = new File("\\src\\baidu");
Systemoutprintln(filegetAbsolutePath());
try
{
Systemoutprintln(filegetCanonicalPath());
} catch (IOException e)
{
eprintStackTrace();
}
}
}
getAbsolutePath()和getCanonicalPath()的不同之处在于,getCanonicalPath()得到的是一个规范的路径,而getAbsolutePath()是用构造File对象的路径+当前工作目录。例如在上面的例子中(点号)代表当前目录。getCanonicalPath()就会把它解析为当前目录但是getAbsolutePath()会把它解析成为目录名字(目录名字是点号)。
下面是上面程序在我电脑上的输出:
G:\xhuoj\konw\\src\baidu
G:\xhuoj\konw\src\baidu
import javaxswing;
import javaxswingtableAbstractTableModel;
import javaxswingtableTableCellRenderer;
import javaxswingeventTreeModelListener;
import javaxswingeventTreeSelectionListener;
import javaxswingeventTreeSelectionEvent;
import javaxswingtreeTreeModel;
import javaxswingtreeTreePath;
import javaxswingtreeTreeCellRenderer;
import javaawt;
import javaawtevent;
import javaioFile;
import javaioFileInputStream;
import javaioIOException;
import javaioFileFilter;
import javautilCalendar;
import javautilArrayList;
import javatextSimpleDateFormat;
import javatextMessageFormat;
/
@author Hardneedl
/
class JavaExplorer extends JFrame {
private static final Dimension minSize = new Dimension(300, 200);
private static final Dimension maxSize = new Dimension(1024, 768);
private static final Dimension preferredSize = new Dimension(600, 400);
private JLabel statusLabel;
private JTree tree;
private JTable detailTable;
private FileTableModel tableModel;
public Dimension getMaximumSize() {return maxSize;}
public Dimension getMinimumSize() {return minSize;}
public Dimension getPreferredSize() {return preferredSize;}
public String getTitle() {return "Java Explorer";}
JavaExplorer() throws HeadlessException {
init();
doLay();
attachListeners();
}
private void init() {
statusLabel = new JLabel(){public Color getForeground() {return ColorBLUE;}};
tree = new JTree(new FileTreeModel());
treesetCellRenderer(new DirCellRenderer());
detailTable = new JTable(tableModel = new FileTableModel());
detailTablegetColumnModel()getColumn(2)setCellRenderer(new TableCellRenderer(){
private JLabel label=new JLabel();
private final SimpleDateFormat format = new SimpleDateFormat("yyyy年mm月dd日 HH时MM分ss秒");
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Calendar){
Calendar cal = (Calendar)value;
labelsetText( formatformat(calgetTime()) );
}
return label;
}
});
detailTablegetColumnModel()getColumn(0)setCellRenderer(new TableCellRenderer(){
private JLabel label = new JLabel();
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof File) {
File f = (File)value;
labelsetText(fgetName());
labelsetForeground( fisDirectory() ColorRED : ColorBLACK);
}
return label;
}
});
}
private void doLay() {
Container container = getContentPane();
JSplitPane splitPane = new JSplitPane(JSplitPaneHORIZONTAL_SPLIT, new JScrollPane(tree), new JScrollPane(detailTable));
containeradd(splitPane,BorderLayoutCENTER);
containeradd(statusLabel,BorderLayoutSOUTH);
pack();
}
private void attachListeners() {
setDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
treeaddTreeSelectionListener(new SelectionListener());
treeaddTreeSelectionListener(new _DirSelectionListener());
DirCellSelectedListener ck =new DirCellSelectedListener(tree);
detailTableaddKeyListener(ck);
detailTableaddMouseListener(ck);
}
public static void main(String[] args) {
new JavaExplorer()setVisible(true);
}
private class FileTreeModel implements TreeModel {
static final String root = "我的电脑";
private File[] rootFiles;
private final FileFilter dirFilter = new FileFilter(){
public boolean accept(File f) {return fisDirectory();}
};
private FileTreeModel() {rootFiles = FilelistRoots();}
public Object getRoot() {return root;}
public Object getChild(Object parent, int index) {
if (parent==getRoot()) return rootFiles[index];
if (parent instanceof File) {
File pf = (File)parent;
return pflistFiles(dirFilter)[index];
}
return null;
}
public int getChildCount(Object parent) {
if (parent == getRoot()) return rootFileslength;
if (parent instanceof File){
File pf = (File)parent;
File[] fs = pflistFiles(dirFilter);
return fs == null0:fslength;
}
return 0;
}
public boolean isLeaf(Object node) {return false;}
public void valueForPathChanged(TreePath path, Object newValue) {}
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
public int getIndexOfChild(Object parent, Object child) {
if (parent == getRoot()) {
for (int i = 0,j=rootFileslength; i < j; i++)
if (rootFiles[i]==child) return i;
}
if (parent instanceof File) {
File pf = (File)parent;
File[] fs = pflistFiles(dirFilter);
for (int i = 0,j=fslength; i < j; i++) {
if (fs[i]equals(child)) return i;
}
}
return -1;
}
}
private class FileTableModel extends AbstractTableModel {
public int getRowCount() {return dir==null||dirisFile()0:dirlistFiles()length;}
public int getColumnCount() {return 3;}
private File dir;
private void setDir(File dir){
thisdir = dir;
fireTableDataChanged();
}
public Class<> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0:return Fileclass;
case 1:return Integerclass;
case 2:return Calendarclass;
default:return Stringclass;
}
}
public String getColumnName(int column) {
switch (column) {
case 0: return "名称";
case 1: return "大小";
case 2: return "修改日期";
default:return "";
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
File[]fs=dirlistFiles();
File f = fs[rowIndex];
switch(columnIndex){
case 0:return f;
case 1:
if (fisDirectory()) return null;
try {
if (fcanRead())
return new FileInputStream(f)available();
} catch (IOException e) {
eprintStackTrace();
}
case 2:
Calendar cl = CalendargetInstance();
clsetTimeInMillis(flastModified());
return cl;
}
return null;
}
}
private class _DirSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
TreePath path = egetNewLeadSelectionPath();
if (path!=null){
Object obj = pathgetLastPathComponent();
if (obj instanceof File) {
File f = (File)obj;
File[] fs = flistFiles();
statusLabelsetText(fs==nullnull:MessageFormatformat("{0}个文件",fslength ));
}
else
statusLabelsetText(null);
}
}
}
private class DirCellRenderer extends JLabel implements TreeCellRenderer {
public boolean isOpaque() {return true;}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (value instanceof File){
String s = ((File)value)getName();
setText(sisEmpty()valuetoString() : s);
}
else
setText(valuetoString());
setForeground(selected ColorBLUE : ColorBLACK);
setBackground(selected ColorYELLOW : ColorWHITE);
return this;
}
}
private class SelectionListener implements TreeSelectionListener{
public void valueChanged(TreeSelectionEvent e) {
Object obj = egetNewLeadSelectionPath()getLastPathComponent();
if (obj instanceof File) {
tableModelsetDir((File)obj);
}
}
}
private class DirCellSelectedListener implements KeyListener, MouseListener {
private JTree tree;
private DirCellSelectedListener(JTree t) {tree=t;}
private void action(InputEvent e){
if (e instanceof MouseEvent) {
}
if (e instanceof KeyEvent) {
}
}
private void expand(File f){
if (fisDirectory()) {
ArrayList<File> L = new ArrayList<File>();
Ladd(f);
File parentFile = fgetParentFile();
while (parentFile != null) {
Ladd(parentFile);
parentFile = parentFilegetParentFile();
}
TreePath treePath = new TreePath(FileTreeModelroot);
for (int i = Lsize()-1; i > -1; i--) {
treePath = treePathpathByAddingChild(Lget(i));
}
treesetSelectionPath(treePath);
}
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if (egetKeyCode() != KeyEventVK_ENTER) return;
if (egetSource() == detailTable) {
int row = detailTablegetSelectedRow();
if (row!=-1){
File f = (File)detailTablegetValueAt(row,0);
expand(f);
}
}
}
public void keyReleased(KeyEvent e) {
}
public void mouseClicked(MouseEvent e) {
if (egetClickCount()==2) {
if(egetSource()==detailTable){
int row = detailTablegetSelectedRow();
if (row!=-1){
File f = (File)detailTablegetValueAt(row,0);
expand(f);
}
}
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
}
在客户端服务器的WCF服务代码里调用ReadFile方法,传入公司服务器上文件的物理路径,即可在客户端服务器端获取到公司服务器文件的二进制流了,之后可以保存下来,也可以直接回发给客户客户端
可以用SQL语句来获取文件:
select Tc from openrowset(bulk N'D:\DB_Backup\E5KST01\audit_trail_20130419bak', single_blob) T(c)
String extend = workergetPhoto()substring(workergetPhoto()
lastIndexOf(""));
// 文件的扩展名
String folder = "/" + GlobeUPLOAD_FOLDER + "/" + workergetUser()getUserName() + "/" + GlobeWORKER_FOLDER + "/";
// 存放上传文件的目录
webfilecreateFolder(getBase(request) + folder);
// 创建文件夹,getBase(request);获得项目的物理路径(在磁盘中的位置)
String imgPath = folder + webtoolgetNowDate(2) + extend;// 产生新的相对路径(不带盘符的)
webfilecopyFile(getBase(request) + workergetPhoto(), getBase(request) + imgPath);// 上传文件(这里只是复制了,因为上传的事情之前已经完成了)
workersetPhoto(imgPath);
// 这个路径是插入数据库的
worker = workerDaoadd(worker);
// 给数据库插入一条记录
查询的时候就能获取插入数据库的路径了。
0条评论