.txt 파일에서 데이터를 읽고 어떻게 표시합니까? 일반적으로.txt 파일에서 데이터 읽기 및 표시
답변
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
그런 다음 in.readLine(); 한 번에 한 줄씩 읽으십시오. 마지막까지 읽으려면 다음과 같이 while 루프를 작성하십시오.
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
in.close()를 추가하는 것을 잊지 마십시오. 귀하의 코드의 끝에. – Brian
파일의 길이를 확인하는 방법은 무엇입니까? –
:
- 이 파일에 대한
FileInputStream
을 만듭니다. - 는
InputStreamReader
올바른 encoding - 가 선택적으로 더 단순 번 라인을 판독 할 수있는 상기 주위
InputStreamReader
BufferedReader
을 만들 지정하여 입력 스트림을 배치 만든다. - 더 이상 데이터가 없을 때까지 읽음 (예 :
readLine
이 null을 반환 함) - 나중을 위해 데이터를 표시하거나 버퍼링합니다.
더 많은 도움이 필요하면 질문에 구체적으로 답해주십시오.
파일이 엄격한 텍스트 인 경우 java.util.Scanner
클래스를 사용하는 것이 좋습니다.
Scanner
를 만들 수 있습니다
:이 있다면 당신은 확인할 수
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
을 그리고 그런 다음
Scanner fileIn = new Scanner(new File(thePathToYourFile));
, 당신은 방법을 사용하여 파일에서 텍스트를 읽을 수 있습니다 더 이상 남은 텍스트 :
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
텍스트를 읽은 다음 텍스트를 String
, 당신은 함께 명령 줄에 문자열을 인쇄 할 수 있습니다
System.out.print(aString);
System.out.println(aString);
게시 된 링크는 스캐너 클래스의 전체 사양이 포함되어 있습니다. 다른 곳에서 할 수있는 일을 돕는 것이 도움이 될 것입니다.
당신은 가능성이 가장 높은 FileInputStream의 클래스를 사용하는 것이 좋습니다 :
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while((character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
또한 읽기() 메소드와 FileInputStream의 생성자에 의해 throw되는 예외의 일부를 잡으려면 것, 그러나 그 구현의 세부 사항에 특정한 귀하의 프로젝트. 당신은 몇 가지 단축키를 먹고 싶어하면
inputStream.read()는 * 문자를 반환하지 않습니다 - i t는 * byte *를 반환합니다 (int로, 틀림없이, 그러나 그들은 아주 다른 것입니다). 텍스트를 읽으려면 독자를 사용해야합니다. –
당신이 사용할 수있는 Apache Commons IO :
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
나는 하나의 문자열로 파일을로드하는 데 사용할,이 코드 조각을 사랑 :
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
행을 읽으려면.encoding UTF-8
와 txt 파일 : 리소스
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
또는 그 경우 :
File krokiPath = new File("Records\Record");
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(krokiPath), "UTF8"));
while((r = in.readLine()) != null) {
System.out.println(r);
}
in.close();
예, 테스트 해 보았습니다. "ąśćłżóź"와 같은 문자를 사용하면 완벽하게 작동합니다. 그것 없이는, 나는이 문자를 사용할 수 없었다. –
인 테 레 스팅. 고맙습니다. – Tom
한 가지 더. UTF-8을 지원하는 앱/객체에서만 작동합니다. –
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
안녕하십니까, StackOverflow에 오신 것을 환영합니다. 도움말 페이지, 특히 [여기에 관해서 내가 무엇에 관해 물을 수있는 주제는 무엇입니까?] (http://stackoverflow.com/help/on-topic) 섹션과 [ "어떤 유형의 질문을해야합니까? 묻지 마시오? "] (http://stackoverflow.com/help/dont-ask). 더 중요한 것은 [Stack Overflow question checklist] (http://meta.stackexchange.com/q/156810/204922)를 읽어보십시오. [Minimal, Complete, Verifiable Examples] (http://stackoverflow.com/help/mcve)에 대해 배우고 싶을 수도 있습니다. –
자바 8에서, 당신은 단순히으로, 전체 파일을 읽을 수 아래
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
스캐너 클래스를 사용하여 파일을 읽고 java로 표시하려고 시도 할 수있는 코드입니다. 코드는 사용자의 파일 이름을 읽고 데이터 (메모장 VIM 파일)를 인쇄합니다.
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
- 1. XML 파일에서 데이터 읽기
- 2. txt 파일에서 사용자 이름과 암호 읽기
- 3. 파일에서 데이터 읽기
- 4. C# - .txt 파일에서 러시아어 텍스트 읽기
- 5. txt 파일에서 double 유형으로 읽기 - C++
- 6. Excel 파일에서 데이터 읽기
- 7. 텍스트 파일에서 데이터 읽기
- 8. 파일에서 데이터 읽기
- 9. Jad 파일에서 데이터 읽기
- 10. .txt 파일 읽기
- 11. .txt 파일과의 정수 읽기 및 쓰기
- 12. 파이썬을 사용하여 .txt 파일에서 데이터 추출하기
- 13. txt 파일에서 Oracle 데이터베이스로 데이터 가져 오기
- 14. 텍스트 파일에서 간단한 텍스트 읽기 및 표시하기
- 15. Android에서 양식 데이터 읽기 및 표시
- 16. 텍스트 파일에서 데이터 읽기 PHP
- 17. XML 파일에서 데이터 읽기 flex
- 18. asp.net의 플랫 파일에서 데이터 읽기
- 19. 다른 디렉토리의 .txt 파일 읽기
- 20. iOS의 텍스트 파일에서 읽기
- 21. 외부에서 생성 된 파일에서 데이터 읽기
- 22. txt 파일에서 바이트 [zip]
- 23. C++ txt 파일 읽기?
- 24. txt 파일에 쓰기/읽기 횟수
- 25. 파일에서 바이트 [] 쓰기 및 읽기
- 26. 박쥐 - 에코가 txt 파일에서 벗어났습니다
- 27. 텍스트 파일에서 변수 읽기
- 28. 원격 서버의 파일에서 헤더 데이터 읽기
- 29. LAMP에서 실행되는 MDB 파일에서 이진 데이터 읽기
- 30. 텍스트 파일에서 특정 줄 읽기 및 쓰기
질문에 좀 더 많은 정보는 아마 당신이 더 나은 답변을 얻을 도움이 될 것이다. 당신이 아는 것에 대한 정보, 당신이 알고 있다고 생각하는 것에 대한 정보 등은 특정 질문이있을 경우 목표를 도울 수 있습니다. –