0

I want to know how can i read the contents of a file, character by character?

I tried this code

Scanner sc = new Scanner(new BufferedReader(newFileReader("C:\\saml.txt")));

while(sc.hasNext())
{
String s=sc.next();
char x[]=s.toCharArray();
for(int i=0;i<x.length;i++)
{
if(x[i]=='\n')
System.out.println("hello");
System.out.println(x[i];
}

I want to give input in file as: "pure world it is"

I want the output "pure hello world hello it hello is hello"

alexandresaiz
  • 2,678
  • 7
  • 29
  • 40
dean
  • 3
  • 4
  • it looks like you'Re not looking for a newline `\n`, but for a space `\s`. – Dragondraikk May 21 '15 at 14:58
  • If you need just detect a newline character, then I'd recommend you to simply read file line-by-line, like [here](http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java). – Eenoku May 21 '15 at 14:58
  • provide what error you are getting – Premraj May 21 '15 at 14:59

2 Answers2

2

Two options:

  1. Compare the string read against System#lineSeparator. If you use Java 6 or prior, use System.getProperty("line.separator");:

    String s = sc.next();
    if (System.lineSeparator().equals(s)) {
        //...
    }
    
  2. Use Scanner#nextLine that will return a String until it finds a line separator character(s) (it will consume the line separator character(s) for you and remove it), then split the string by empty spaces and work with every string between spaces.

    String s = sc.nextLine();
    String[] words = s.split("\\s+");
    for (String word : words) {
        //...
    }
    

Note that in any of these cases you don't need to evaluate each character in the String.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

I would suggest using Scanner.nextLine and either using String.join(java 8+) or going for the manual method:

Without a trailing "hello":

        while (sc.hasNext()){
            String[] words = sc.nextLine().split(" ");
            String sentence = words[0];
            for(int i = 0; ++i < words.length;)
                sentence += " hello " + words[i];
            System.out.println(sentence);
        }

With a trailing "hello":

        while (sc.hasNext()){
            for(String w : sc.nextLine().split(System.getProperty("line.separator")))
                System.out.print(w + " hello ");
            System.out.println();
        }
Emil
  • 23
  • 4