0

I have a constructor looks like this:

MyClassName(File f) throws Exception;

and a txt file looks like this:

. . . . .
. . . . .
. x . . .
. x x . .
. . . . .
. . . . .

When open the file, how do I convert it to a String?

Like this:

". . . . .\n
. . . . .\n
. x . . .\n
. x x . .\n
. . . . .\n
. . . . .\n"
Jason
  • 1
  • 2
  • It's unclear what you mean - it sort of sounds like you want to create a string literal, but you can't have multi-line string literals (not without explicitly concatenating the lines, anyway). – Andy Turner Apr 24 '16 at 22:07
  • 2
    `new String(Files.readAllBytes(f.toPath()))` – Elliott Frisch Apr 24 '16 at 22:10
  • @ElliottFrisch worth mentioning the file encoding here - platform default might not be correct. Although it shouldn't have much of an impact given the content. – Boris the Spider Apr 24 '16 at 22:12

1 Answers1

0

this method reads a file:

 public String readFile(File file) {
    StringBuffer stringBuffer = new StringBuffer();
    if (file.exists())
        try {
            //read data from file
            FileInputStream fileInputStream = new FileInputStream(file);
            int c;
            while ((c = fileInputStream.read()) != -1){
                stringBuffer.append((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    return stringBuffer.toString();
}

and the call from the constructor

public MyClassName(File f) throws Exception{
     String text = readFile(f);
}
Sadik anass
  • 282
  • 4
  • 9