• Post Reply Bookmark Topic Watch Topic
  • New Topic

java IO

 
sven sederberg
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have following code:






import java.io.*;

public class Gramata {
public static void main (String[] args) {

int num_lines = 0;
File file = new File("D://myfile.txt");

// PrintWriter out = new PrintWriter(new FileWriter(myTextTxt));

// File myTextTxt = new File ("c://someDir//someAnotherDir//mytext.txt"); //<<<< šinī vietā pamēģini slash-us likt uz abām pusēm.

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Vai jūs gribat apskatīt sarakstu(ja|ne)?");
if("ja".equalsIgnoreCase(reader.readLine())){ //<<<< šinī vietā reader ielasīs visu līdz ENTER nospiešanai.

try {

// Izveido buferizētu lasītāju lasīšanai no standartievades
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));
// Izveido 'PrintWriter' instanci šim failam
PrintWriter out
= new PrintWriter(new FileWriter("myfile.txt"));
String s;

System.out.print("Ievadiet tekstu ");
System.out.println("[Ievades beigas: Ctrl-z]");

// Lasīt pa rindiņām un izvadīt tās failā
while ((s = in.readLine()) != null) {
out.println(s);
}

// Aizvērt konsoles lasītāju un faila rakstītāju
in.close();
out.close();

} catch (IOException e) {
// Apstrādā I/O izņēmumus
e.printStackTrace();
}
}

else
try {

// Izveido buferizētu lasītāju, lai lasītu pa rindiņām
BufferedReader in = new BufferedReader(new FileReader("myfile.txt"));
String s;

// Nolasa rindiņu un atbalso to uz ekrāna
s = in.readLine();
while ( s != null ) {
System.out.println("Read: " + s);
s = in.readLine();
}
// Aizver buferizētu lasītāju, kurš aizver arī faila lasītāju
in.close();

} catch (FileNotFoundException e1) {
// Ja fails neeksistē
System.err.println("File not found: " + file);
//System.err.println("File not found: " + file);

} catch (IOException e2) {
// Apstrādā citus I/O izņēmumus
e2.printStackTrace();
}


}
}






I can`t compile useing Eclipse.
There is error in line 15:

java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException

at Gramata.main(Gramata.java:15)
Exception in thread "main"



Actually I want execute if or else block in case of input parameter.


Can somebody help me? Thanks!
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

I would guess that this line:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));


can throw in IOException, which you need to handle. Why don't you put all of the code in of a try/catch statement?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!