Skip to content

Instantly share code, notes, and snippets.

@tnhansel
Created December 3, 2013 22:07
Show Gist options
  • Save tnhansel/7778397 to your computer and use it in GitHub Desktop.
Save tnhansel/7778397 to your computer and use it in GitHub Desktop.
Read data from .txt
import java.util.Scanner;
public class ReadData
{
public static void main(String[] args) throws Exception
{
String message; // holding the line coming from the source
// creating the file class and giving its excat location
java.io.File x = new java.io.File("/Users/hanseltan/Documents/hello world.txt");
// Create a Scanner named y to read the input stream from the file x
Scanner y = new Scanner(x);
// Reading the file
message = y.nextLine();
// print the message from the file on the screen
System.out.println("reading from the data file...\n");
System.out.println(message);
// closing connection
y.close();
}
}
@danggrianto
Copy link

java.io.File x = new java.io.File("/Users/hanseltan/Documents/hello world.txt"); ini ga perlu dek atas kmau import dulu
import java.io.File trus statement itu jadi File x = new File("/Users/hanseltan/Documents/hello world.txt"); trus kalo misalnya kamu pake absolute file path "/Users/hanseltan/Documents/hello world.txt" misalnya program ini koko execute di komputer koko file ini ga ada... better km just put "helloworld.txt" trus file ini disimpen di folder yg sama buat ReadData.java

@danggrianto
Copy link

Scanner y = new Scanner(x); buat ini koko not sure if scanner class can actually read file. But i might be wrong. if this program can run then i think it is okay.

@danggrianto
Copy link

message = y.nextLine(); ini oke kalo misalnya dek dalem text file cuma ada satu line tapi kalo misalnya lebih dari satu line then line berikutnya ga kebaca.. kamu mesti taru ini dek dalem for loops.

while(y.hasNext()){
    // Reading the file
    message = y.nextLine();

    // print the message from the file on the screen
    System.out.println(message);
}

maybe this one better again i am not sure if y.hasNext() works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment