2017-10-13 10 views
0

Comment utiliser un chemin de fichier spécifié plutôt qu'un fichier du dossier de ressources en tant que flux d'entrée ou de sortie? C'est la classe que j'ai et je voudrais lire à partir d'un chemin de fichier spécifique au lieu de placer le fichier txt dans le dossier des ressources dans IntelliJ. Idem pour un flux de sortie. Toute aide apportée serait appréciée merci.Flux d'entrée et de sortie Java à partir du chemin de fichier

flux d'entrée

import java.io.*; 
import java.util.*; 

public class Example02 { 
    public static void main(String[] args) throws FileNotFoundException { 
     // STEP 1: obtain an input stream to the data 

     // obtain a reference to resource compiled into the project 
     InputStream is = Example02.class.getResourceAsStream("/file.txt"); 

     // convert to useful form 
     Scanner in = new Scanner(is); 

     // STEP 2: do something with the data stream 
     // read contents 
     while (in.hasNext()) { 
      String line = in.nextLine(); 
      System.out.println(line); 
     } 

     // STEP 3: be polite, close the stream when done! 
     // close file 
     in.close(); 
    } 
} 

flux de sortie

import java.io.*; 

public class Example03 
{ 
    public static void main(String []args) throws FileNotFoundException 
    { 
     // create/attach to file to write too 
     // using the relative filename will cause it to create the file in 
     // the PROJECT root 
     File outFile = new File("info.txt"); 

     // convert to a more useful writer 
     PrintWriter out = new PrintWriter(outFile); 

     //write data to file 
     for(int i=1; i<=10; i++) 
      out.println("" + i + " x 5 = " + i*5); 

     //close file - required! 
     out.close();    
    } 
} 
+2

FileInputStream – GurV

Répondre

-1

Vous pouvez utiliser un objet de fichier comme:

File input = new File("C:\\[Path to file]\\file.txt"); 
0

D'abord, vous devez définir le chemin que vous voulez lire le fichier de, abso chemin luth comme ceci:

String absolutePath = "C:/your-dir/yourfile.txt" 
InputStream is = new FileInputStream(absolutePath); 

Il est similaire pour écrire le fichier ainsi:

String absolutePath = "C:/your-dir/yourfile.txt" 
PrintWriter out = new PrintWriter(new FileOutputStream(absolutePath));