1. 程式人生 > >從TFTPDemo看檔案流FileInputStream/FileOutputStream的使用

從TFTPDemo看檔案流FileInputStream/FileOutputStream的使用

    我這個人,腦子有點 笨,對java中的輸入輸出流的概念瞭解不透。
    今天,通過這個demo,算是真正理解了。
    這個TFTP的demo,首先是建立以TFTPClient物件,設定超時,開啟網路連線。
    TFTPClient client = new TFTPClient();
    如果是接收檔案,因為要把遠端檔案寫到本地,所有要建立一個本地檔案:
    File file = new File(localFile);
    然後,用FileOutputStream來包裝(wrap)這個檔案:
    FileOutputStream out = new FileOutputStream(file);
    接下來,呼叫client的接收檔案的方法,把遠端檔案,通過FileOutputStream這樣的流,寫到本地:
    client.receiveFile(remoteFile, TFTP.BINARY,out,hostName);
    最後,關閉連結。

    如果是傳送檔案,只用把本地檔案讀取到FileInputStream這流中:
    FileInputStream input = new FileInputStream(localFile);
    接下來,呼叫client的傳送檔案的方法傳送檔案:
    client.sendFile(remoteFile, TFTP.BINARY, input, hostName);
    最後,關閉連結。
   
    完整程式碼:
package examples;


/*
 * Copyright 2001-2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     
http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 
*/



import java.io.File;
import java.io.FileInputStream;
import
 java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.commons.net.tftp.TFTP;
import org.apache.commons.net.tftp.TFTPClient;

/***
 * This is an example of a simple Java tftp client using NetComponents.
 * Notice how all of the code is really just argument processing and
 * error handling.
 * <p>
 * Usage: tftp [options] hostname localfile remotefile
 * hostname   - The name of the remote host
 * localfile  - The name of the local file to send or the name to use for
 *              the received file
 * remotefile - The name of the remote file to receive or the name for
 *              the remote server to use to name the local file being sent.
 * options: (The default is to assume -r -b)
 *        -s Send a local file
 *        -r Receive a remote file
 *        -a Use ASCII transfer mode
 *        -b Use binary transfer mode
 * <p>
 **
*/

publicclass TFTPDemo
{
    
staticfinal String USAGE =
        
"Usage: tftp [options] hostname localfile remote    file "+
        
"hostname   - The name of the remote host "+
        
"localfile  - The name of the local file to send or the name to use for "+
        
" the received file "+
        
"remotefile - The name of the remote file to receive or the name for "+
        
" the remote server to use to name the local file being sent. "+
        
"options: (The default is to assume -r -b) "+
        
" -s Send a local file "+
        
" -r Receive a remote file "+
        
" -a Use ASCII transfer mode "+
        
" -b Use binary transfer mode ";

    
publicfinalstaticvoid main(String[] args)
    
{
        
boolean receiveFile =true, closed;
        
int transferMode = TFTP.BINARY_MODE, argc;
        String arg, hostname, localFilename, remoteFilename;
        TFTPClient tftp;

        
// Parse options
for (argc =0; argc < args.length; argc++)
        
{
            arg 
= args[argc];
            
if (arg.startsWith("-"))
            
{
                
if (arg.equals("-r"))
                    receiveFile 
=true;
                
elseif (arg.equals("-s"))
                    receiveFile 
=false;
                
elseif (arg.equals("-a"))
                    transferMode 
= TFTP.ASCII_MODE;
                
elseif (arg.equals("-b"))
                    transferMode 
= TFTP.BINARY_MODE;
                
else
                
{
                    System.err.println(
"Error: unrecognized option.");
                    System.err.print(USAGE);
                    System.exit(
1);
                }

            }

            
else
                
break;
        }


        
// Make sure there are enough arguments
if (args.length - argc !=3)
        
{
            System.err.println(
"Error: invalid number of arguments.");
            System.err.print(USAGE);
            System.exit(
1);
        }


        
// Get host and file arguments
        hostname = args[argc];
        localFilename 
= args[argc +1];
        remoteFilename 
= args[argc +2];

        
// Create our TFTP instance to handle the file transfer.
        tftp =new TFTPClient();

        
// We want to timeout if a response takes longer than 60 seconds
        tftp.setDefaultTimeout(60000);

        
// Open local socket
try
        
{
            tftp.open();
        }

        
catch (SocketException e)
        
{
            System.err.println(
"Error: could not open local UDP socket.");
            System.err.println(e.getMessage());
            System.exit(
1);
        }


        
// We haven't closed the local file yet.
        closed =false;

        
// If we're receiving a file, receive, otherwise send.
if (receiveFile)
        
{
            FileOutputStream output 
=null;
            File file;

            file 
=new File(localFilename);

            
// If file exists, don't overwrite it.
if (file.exists())
            
{
                System.err.println(
"Error: "+ localFilename +" already exists.");
                System.exit(
1);
            }


            
// Try to open local file for writing
try
            
{
                output 
=new FileOutputStream(file);
            }

            
catch (IOException e)
            
{
                tftp.close();
                System.err.println(
"Error: could not open local file for writing.");
                System.err.println(e.getMessage());
                System.exit(
1);
            }


            
// Try to receive remote file via TFTP
try
            
{
                tftp.receiveFile(remoteFilename, transferMode, output, hostname);
            }

            
catch (UnknownHostException e)
            
{
                System.err.println(
"Error: could not resolve hostname.");
                System.err.println(e.getMessage());
                System.exit(
1);
            }

            
catch (IOException e)
            
{
                System.err.println(
                    
"Error: I/O exception occurred while receiving file.");
                System.err.println(e.getMessage());
                System.exit(
1);
            }

            
finally
            
{
                
// Close local socket and output file
                tftp.close();
                
try
                
{
                    output.close();
                    closed 
=true;
                }

                
catch (IOException e)
                
{
                    closed 
=false;
                    System.err.println(
"Error: error closing file.");
                    System.err.println(e.getMessage());
                }

            }


            
if (!closed)
                System.exit(
1);

        }

        
else
        
{
            
// We're sending a file
            FileInputStream input =null;

            
// Try to open local file for reading
try

相關推薦

TFTPDemo檔案FileInputStream/FileOutputStream的使用

    我這個人,腦子有點 笨,對java中的輸入輸出流的概念瞭解不透。    今天,通過這個demo,算是真正理解了。    這個TFTP的demo,首先是建立以TFTPClient物件,設定超時,開啟網路連線。    TFTPClient client = new TFT

檔案位元組FileInputStream,FileOutputStream

1.從檔案讀取資訊到記憶體(位元組)         File f = new File("/Users/hh/Desktop/test豆腐缶122.txt"); //因為file沒有讀寫的能力,所以需要FileI

JAVA學習--檔案FileInputStreamFileOutputStream操作

* 1.流的分類:  * 按照資料流向的不同:輸入流  輸出流  * 按照處理資料的單位的不同:位元組流  字元流(處理的文字檔案)  * 按照角色的不同:節點流(直接作用於檔案的)  處理流  *   * 2

檔案FileInputStream 把一個檔案的內容轉到另一個檔案

import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOE

檔案位元組FileInputStreamFileOutputStream

1.完成基本檔案複製 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStrea

Java 檔案一:位元組FileInputStreamFileOutputStream

   Java檔案流操作是一個非常重要的內容。下圖列舉了關於Java基本的檔案流操作,當然目前還有NIO,這個後來會進行討論,先看基本的檔案流操作。我們主要使用的是訪問檔案的流和緩衝流。   檔案的流操作一般包含字元流和位元組流,兩者區別在於,字元流每次傳播16bit資

CC++之(八)檔案操作

    Linux平臺下提供了標準的C庫API實現對檔案的讀寫操作,同樣C++也提供了自身對檔案流操作的一些手段.雖然不知道以後會不會用到,但是瞭解一下是很有必要的. 原始碼: #include <iostream> #include <fstream&

FileInputStream讀取檔案頁碼後,檔案被改變

如下程式碼,fis在讀取檔案頁碼操作後實際已被改變,若仍然用此物件,獲取到的md5有誤,為空或一固定值d41d8cd98f00b204e9800998ecf8427e 處理方法多設定一個fis2,用於後續操作 FileInputStream fis = (FileInput

minio中讀取檔案進行下載檔案

一、獲取Minio連線     public static String minioUrl;         public static String minioUsername;    

JavaI/O:簡單的使用FileInput和FileOutputStream操作檔案

  java的輸入輸出建立在4個抽象類的基礎上:InputStream、OutputStream、Reader、Writer。InputSream和OutputStream被設計成位元組流類,而Reader和Writer被設計成字元流類。一般來說,處理字元或者字串時應該使用字元流類,處理位元組或者二

原始碼Spark讀取Hive表資料小檔案和分塊的問題

原文連結:https://mp.csdn.net/postedit/82423831  使用Spark進行資料分析和計算早已成趨勢,你是否關注過讀取一張Hive表時Task數為什麼是那麼多呢?它跟什麼有關係呢? 最近剛好碰到這個問題,而之前對此有些模糊,所以做了些整理,希望大家拍磚探討

使用 FileInputStream / FileOutputStream 複製檔案

使用 FileInputStream / FileOutputStream 複製檔案 code: /** * @param source 必須存在此檔案 * @param aim 此檔案可以不存在 * @throws IOException 可能會丟擲的異常 *

【原創】原始碼剖析IO(二)檔案--轉載請註明出處

一、FileInputStream 在FileInputStream中,首先我們需要進行關注的方法,就是read()方法,下面可以來看一下read()方法的原始碼: public int read() throws IOException { return read0()

C語言fread()函式:讀檔案函式(檔案讀取資料)

相關函式:fopen, fwrite, fseek, fscanf標頭檔案:#include <stdio.h>定義函式:size_t fread(void * ptr, size_t size, size_t nmemb, FILE * stream);函式說

檔案/檔案的頭位元組中得到mime資訊

在寫網路爬蟲的時候,需要根據連結來獲取檔案型別,將內容正確儲存。之前我都是根據連結的字尾來判斷的,比如: http://img12.360buyimg.com/da/20120330/88_31_ZySDre.jpg 這個連結指向的檔案就是個jpg檔案。但是後來發現有

核心檔案系統檔案讀寫過程

回到頂部系統呼叫作業系統的主要功能是為管理硬體資源和為應用程式開發人員提供良好的環境,但是計算機系統的各種硬體資源是有限的,因此為了保證每一個程序都能安全的執行。處理器設有兩種模式:“使用者模式”與“核心模式”。一些容易發生安全問題的操作都被限制在只有核心模式下才可以執行,例

FTP下載圖片返回檔案在頁面顯示圖片

.HTML <div id="showPicture" style="width:100%;height:800px;line-height:100px;overflow:auto;overflow-x:hidden; text-align: center;">

request中獲取檔案的兩種方式

Collection<Part> parts = req.getParts(); for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext();) {     Part part = iterator.next(

Java ioFileOutputStreamFileInputStream 詳解

FileOutputStream 檔案輸出流 方法程式碼詳解: public class Demo01 { public static void main(String[] a