Home > Net >  Read and print file char by char
Read and print file char by char

Time:02-10

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();

CodePudding user response:

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.

  •  Tags:  
  • Related