Reading and displaying data from a .txt file

后端 未结 10 870
北海茫月
北海茫月 2020-11-27 15:41

How do you read and display data from .txt files?

相关标签:
10条回答
  • 2020-11-27 15:57

    In Java 8, you can read a whole file, simply with:

    public String read(String file) throws IOException {
      return new String(Files.readAllBytes(Paths.get(file)));
    }
    

    or if its a Resource:

    public String read(String file) throws IOException {
      URL url = Resources.getResource(file);
      return Resources.toString(url, Charsets.UTF_8);
    }
    
    0 讨论(0)
  • 2020-11-27 15:59

    I love this piece of code, use it to load a file into one String:

    File file = new File("/my/location");
    String contents = new Scanner(file).useDelimiter("\\Z").next();
    
    0 讨论(0)
  • 2020-11-27 16:00
    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();
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 16:04

    In general:

    • Create a FileInputStream for the file.
    • Create an InputStreamReader wrapping the input stream, specifying the correct encoding
    • Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
    • Read until there's no more data (e.g. readLine returns null)
    • Display data as you go or buffer it up for later.

    If you need more help than that, please be more specific in your question.

    0 讨论(0)
提交回复
热议问题