-1

I am reading and then printing this file char by char but now I would like to print 20 chars by 20 chars, incrementig the i value like i+=20 is not what i want.

File fitxer = new File ("C:\\Users\\yuto\\IdeaProjects\\M6-DataAccess\\src\\UF1\\FluxesAndStreams\\A1.java"); 
            FileReader flux = new FileReader (fitxer); 
            int i;
            while ((i = flux.read()) != -1) { 
    
                System.out.println((char) i); 
            }
            flux.close();
aizeenX
  • 21
  • 6
  • Does this answer your question? [Java: print contents of text file to screen](https://stackoverflow.com/questions/15695984/java-print-contents-of-text-file-to-screen) – rikyeah Feb 09 '22 at 19:25
  • @rikyeah I added an answer, I just wanted to print a character every twenty chars. – aizeenX Feb 15 '22 at 17:19

2 Answers2

1

You can use aux variables like that:

File fitxer = new File ("C:\\Users\\yuto\\IdeaProjects\\M6-DataAccess\\src\\UF1\\FluxesAndStreams\\A1.java"); 
FileReader flux = new FileReader (fitxer); 
int i;
byte aux = 0;
String s = "";
while ((i = flux.read()) != -1) { 
    if (20 == aux){
        System.out.println(s);
        s = "";
        aux = 1
    }
    s+=i;
    aux++;
}
flux.close();

or you can use the read overloaded method in FileReader who does exactly the same thing.

/* method signature
 * cbuf - Destination buffer
 * offset - Offset at which to start storing characters
 * length - Maximum number of characters to read
 */
public int read(char[] cbuf, int offset, int length) // return the number of bytes read

example of read method mentioned above: https://www.tutorialspoint.com/java/io/inputstreamreader_read_char.htm

note the FileRead inherits read method from InputStreamReader.

Marcio Rocha
  • 186
  • 2
  • 9
0

Another way;

File fitxer = new File ("C:\\Users\\yuto\\IdeaProjects\\M6-DataAccess\\src\\UF1\\FluxesAndStreams\\A1.java"); 
            FileReader flux = new FileReader (fitxer); 
            int i, count = 0;

            while ((i = flux.read()) != -1) { 
                count++;
                if(count % 20 == 0) System.out.println((char) i); 
                //or ternary operator
                System.out.println((count % 20 == 0 ? (char) i : "")); 
            }
            flux.close();
aizeenX
  • 21
  • 6