Last active
December 2, 2020 12:27
-
-
Save emersonmello/a760feb099983ab901cd2782d0229b95 to your computer and use it in GitHub Desktop.
Para obter um arquivo do disco, pela IDE e quando estiver em arquivo JAR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package poo; | |
import java.io.InputStream; | |
import java.util.Scanner; | |
public class ArquivoERecurso { | |
public static void main(String[] args) { | |
System.out.println("Trabalhando com arquivos"); | |
Principal p = new Principal(); | |
p.lerArquivo(); | |
} | |
public void lerArquivo() { | |
// Para pegar o arquivo quando estiver dentro um .jar | |
InputStream is = getClass().getResourceAsStream("/resources/produtos.txt"); | |
// Para pegar o arquivo quando estiver executando pela IDE | |
if (is == null){ | |
is = getClass().getClassLoader().getResourceAsStream("produtos.txt"); | |
} | |
try { | |
Scanner leitor = new Scanner(is); | |
// varrendo o conteúdo do arquivo linha por linha | |
while (leitor.hasNextLine()) { | |
System.out.println(leitor.nextLine()); | |
} | |
} catch (Exception e) { | |
System.err.println("Erro ao tentar ler o arquivo: " + e.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment