1. 程式人生 > >Unity3D與JAVA服務器傳遞文件之服務器端

Unity3D與JAVA服務器傳遞文件之服務器端

log seek ring pos con 文件中 utf 回車 服務

  • 剛好工作中有用到,特此來記錄一下,JAVA服務器用的是JFinal框架。
    • Unity上傳文件只能傳輸字節流,然後服務器這邊再將字節流寫入文件
    • public void uploadFile() throws IOException {
              renderNull();        
              //==================開始處理文件===================
      
              //接收上傳文件內容中臨時文件的文件名
              System.out.println(getRequest().getContentLength());
              
      if(getRequest().getContentLength()>0){ String tempFileName = new String("tempFileName.txt"); //tempfile 對象指向臨時文件 File tempFile = new File(PathKit.getWebRootPath() + File.separator+tempFileName); System.out.println("FilePath:"+PathKit.getWebRootPath() + File.separator+tempFileName);
      //outputfile 文件輸出流指向這個臨時文件 FileOutputStream outputStream = new FileOutputStream(tempFile); //得到客戶端提交的所有數據 InputStream fileSourcel = getRequest().getInputStream(); //將得到的客戶端數據寫入臨時文件 byte b[] = new byte[1000]; int n ; while ((n=fileSourcel.read(b))!=-1){ System.out.println(
      "b:"+b); System.out.println("n:"+n); outputStream.write(b,0,n); } //關閉輸出流和輸入流 outputStream.close(); fileSourcel.close(); //randomFile對象指向臨時文件 RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r"); //讀取臨時文件的前三行數據 randomFile.readLine(); randomFile.readLine(); randomFile.readLine(); //讀取臨時文件的第四行數據,這行數據中包含了文件的路徑和文件名 String filePath = randomFile.readLine(); //得到文件名 System.out.println(filePath); int position = filePath.lastIndexOf("filename"); String filename =Tool.codeString(filePath.substring(position+10,filePath.length()-1)); System.out.println("filename"+filename); //重新定位讀取文件指針到文件頭 randomFile.seek(0); //得到第五行回車符的位置,這是上傳文件數據的開始位置 long fifthEnterPosition = 0; int fifth = 1; while((n=randomFile.readByte())!=-1&& fifth<=5)){ System.out.println("n:"+n); System.out.println( fifth:" fifth); if(n==‘\n‘){ fifthEnterPosition = randomFile.getFilePointer(); fifth++; } System.out.println( fifthEnterPosition:" fifthEnterPosition); } //生成上傳文件的目錄 File fileupLoad = new File(PathKit.getWebRootPath() + File.separator,"upLoad"); fileupLoad.mkdir(); //saveFile 對象指向要保存的文件 File saveFile = new File(PathKit.getWebRootPath() +"\\upLoad",filename); RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw"); //找到上傳文件數據的結束位置,即倒數第三行 randomFile.seek(randomFile.length()); long endPosition = randomFile.getFilePointer(); System.out.println("endPosition:"+endPosition); int j = 1; while((endPosition>=0)&&(j<=3)){ System.out.println("endPosition1:"+endPosition); System.out.println("j:"+j); endPosition--; randomFile.seek(endPosition); if(randomFile.readByte()==‘\n‘){ j++; } } //從上傳文件數據的開始位置到結束位置,把數據寫入到要保存的文件中 System.out.println( fifthEnterPosition:" fifthEnterPosition); randomFile.seek fifthEnterPosition); long startPoint = randomFile.getFilePointer(); System.out.println("startPoint:"+startPoint); //endPosition=randomFile.getFilePointer(); System.out.println("endPosition:"+endPosition); while(startPoint<endPosition){ System.out.println("startPoint1:"+startPoint); //System.out.println("randomFile.readByte():"+randomFile.readByte()); randomAccessFile.write(randomFile.readByte()); startPoint = randomFile.getFilePointer(); } //關閉文件輸入、輸出 randomAccessFile.close(); randomFile.close(); tempFile.delete(); //==================處理文件結束=================== //向控制臺輸出文件上傳成功 System.out.println("File upload success!"); checkCsv(); }else{ renderText("false"); } }
    • public class Tool {
      
          /** 文件字節流 */
          public static byte[] getBytes(String filePath) {
              byte[] buffer = null;
              try {
                  File file = new File(filePath);
                  FileInputStream fis = new FileInputStream(file);
                  ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
                  byte[] b = new byte[1000];
                  int n;
                  while ((n = fis.read(b)) != -1) {
                      bos.write(b, 0, n);
                  }
                  fis.close();
                  bos.close();
                  buffer = bos.toByteArray();
              } catch (FileNotFoundException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              }
              return buffer;
          }
      
          /** 處理中文字符串的函數 */
          public static String codeString(String str) {
              String s = str;
              try {
                  byte[] temp = s.getBytes("UTF-8");
                  s = new String(temp);
                  return s;
              } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
                  return s;
              }
          }
      }

    • 用網頁上傳與字節流傳輸完全不一樣
    • public void uploadFileWeb() throws IOException {
              UploadFile uploadFile = this.getFile();
              String fileName = uploadFile.getOriginalFileName();
              File file = uploadFile.getFile();
              FileService fs = new FileService();
              File t = new File("D:\\file\\" + fileName); 
              try {
                  t.createNewFile();
              } catch (IOException e) {
                  e.printStackTrace();
              }
              fs.fileChannelCopy(file, t);
              file.delete();
          }
    • 下載文件用的是JFinal的renderFile
    • // 下載文件
          public void downfile() throws FileNotFoundException, IOException {
              readfiles("D:\\file\\");
              String name = getPara("filename");
              System.out.println(name);
              int index = -1;
              for (int i = 0; i < filearraylist.size(); i++) {
                  if (filearraylist.get(i).indexOf(name) != -1) {
                      index = i;
                  }
              }
              System.out.println(index);
              if (index > -1) {
                  renderFile(new File(filearraylist.get(index)));
                  System.out.println(filearraylist.get(index));
              }
          }
      
          // 遞歸獲取目錄下的所有文件
          public static boolean readfiles(String filepath) throws FileNotFoundException, IOException {
              try {
                  File file = new File(filepath);
                  if (!file.isDirectory()) {
                      System.out.println("文件");
                      System.out.println("path=" + file.getPath());
                      System.out.println("absolutepath=" + file.getAbsolutePath());
                      System.out.println("name=" + file.getName());
                      filearraylist.add(file.getPath());
                      // filearraylist.add("<a href=‘/file/downfile‘>下載</a><br>");
                  } else if (file.isDirectory()) {
                      System.out.println("文件夾");
                      String[] filelist = file.list();
                      for (int i = 0; i < filelist.length; i++) {
                          File readfile = new File(filepath + "\\" + filelist[i]);
                          if (!readfile.isDirectory()) {
                              System.out.println("path=" + readfile.getPath());
                              System.out.println("absolutepath=" + readfile.getAbsolutePath());
                              System.out.println("name=" + readfile.getName());
                              filearraylist.add(readfile.getPath());
                          } else if (readfile.isDirectory()) {
                              readfiles(filepath + "\\" + filelist[i]);
                          }
                      }
                  }
              } catch (FileNotFoundException e) {
                  System.out.println("readfile()   Exception:" + e.getMessage());
              }
              return true;
          }

Unity3D與JAVA服務器傳遞文件之服務器端