2015-01-02 1 views

Antwort

22

Die java.io.File-Klasse enthält vier statische Separatorvariablen. Zum besseren Verständnis, lassen Sie uns mit Hilfe eines Codes verstehen

  1. Separator: Plattformabhängige Standardname-Trennzeichen als String. Für Windows ist es '\' und für UNIX ist es '/'
  2. separatorChar: Wie Trennzeichen, aber es ist char
  3. pathSeparator: Plattformabhängige Variable für Pfadtrennzeichen. Für Beispiel PATH oder CLASSPATH Variable Liste von Pfaden durch ':' getrennt in Unix-Systemen und ';' in Windows-System
  4. pathSeparatorChar: Wie PathSeparator aber es ist char

Beachten Sie, dass alle diese sind endgültig Variablen und systemabhängig.

Hier ist das Java-Programm zum Drucken dieser Separatorvariablen. FileSeparator.java

import java.io.File; 

public class FileSeparator { 

    public static void main(String[] args) { 
     System.out.println("File.separator = "+File.separator); 
     System.out.println("File.separatorChar = "+File.separatorChar); 
     System.out.println("File.pathSeparator = "+File.pathSeparator); 
     System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar); 
    } 

} 

Ausgabe des obigen Programms auf Unix-System:

File.separator =/
File.separatorChar =/
File.pathSeparator = : 
File.pathSeparatorChar = : 

Ausgabe des Programms auf Windows-System:

File.separator = \ 
File.separatorChar = \ 
File.pathSeparator = ; 
File.pathSeparatorChar = ; 

Um unser Programm plattformunabhängig zu machen, sollten wir Verwenden Sie diese Trennzeichen immer zum Erstellen eines Dateipfads oder zum Lesen beliebiger Systemvariablen wie PATH oder CLASSPATH.

Hier ist das Code-Snippet, das zeigt, wie Sie Separatoren korrekt verwenden.

//no platform independence, good for Unix systems 
File fileUnsafe = new File("tmp/abc.txt"); 
//platform independent and safe to use across Unix and Windows 
File fileSafe = new File("tmp"+File.separator+"abc.txt"); 
+1

pathSeparator ist SO irreführend ... Warum nicht make pathVariableSeparator oder classpathSeparator? –

Verwandte Themen