read output of txt file has white spaces

2020-04-16 03:17发布

问题:

i got the list of applications from cmd command using /output:D:\list.txt product get name,version. However when i try to retrieve the list using java the output has white spaces after each letter.

SAMPLE:

from text file

links

images

lists

when read in java

 l i n k s

 i m a g e s 

 l i s t s

is there a way to fix this problem?

i just used this code:

public void myreader() throws IOException {
 Path path = Paths.get("D:\\list.txt");
 Charset charset = Charset.forName("ISO-8859-1");
 try (BufferedReader reader = Files.newBufferedReader(path,charset)) {
      String line = null;
      while ((line = reader.readLine()) != null) {
           System.out.println(line);
      }
 }

回答1:

This can be due to the encoding problem. Try using UTF-16 character set

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-16"));


回答2:

Have you tried the FileReader?

FileReader fileReader;
try {
    fileReader = new FileReader( "D:\\list.txt" );
    BufferedReader bufferedReader = new BufferedReader( fileReader ); 
    String line; 
    while( ( line = bufferedReader.readLine() ) != null )
    { 
        System.out.println( line ); 
    }
    fileReader.close();
} catch ( IOException except ) {
    System.err.println( except.getStackTrace()[0] );
}

Im not shure where your problem is coming from, but you may take the FileReader for such instructions.



回答3:

Looks like you read a UTF-16 encoded file.

Give a hint to your Reader - pass "UTF-16", instead of "ISO-8859-1".



标签: java windows cmd