Categorie
Linux Programmazione Windows

Java Console and File Input Output Cheat Sheet

Console Output

System.out.print("Hello ");
System.out.println("world");

Console Input

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String text = in.readLine();

File Output

String filename= "MyFile.txt";
PrintWriter out = new PrintWriter(new FileWriter(filename,true)));//the true will append the new data
out.print("Hello ");
out.close();

File Input

BufferedReader in = new BufferedReader(new FileReader("K:\\location\\inputfile.txt"));
String text = in.readLine();
in.close();

Converting input data

String text  = in.readLine();
int x = Integer.parseInt(text);
double y = Double.parseDouble(text);

Reading until EOF

while (in.ready()) {
  text = in.readLine();
  System.out.println(text);
}

Pulling apart delimited items on a line

String text = "Beggars in Spain*Nancy Kress*1992";
StringTokenizer tokenizer = new StringTokenizer(text,"*");
String title = tokenizer.nextToken();
String author = tokenizer.nextToken();
String year = tokenizer.nextToken();

String letters = "a b c d e f g h i j";
StringTokenizer tokenizer = new StringTokenizer(text," ");
String[] allText = new String[10];
int pos = 0;
while (tokenizer.hasMoreTokens())
      allText[pos++] = tokenizer.nextToken();

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.