我正在尝试读取和打印每个字符,并在其旁边留有空格(在txt文件的第3行之后)。如何在每个字符后添加空格?
我的输入文件txt如下所示(忽略前3行:]
6111211 211111 T.T ... ...... .... T。 .... T。 TTT ... ......
我要打印的是:。 。 。 。。 。 。 。 。 。。 。 。 。 。。 。 。 。 。T 。 。。 。 。 。 。 。
public static void main(String[] args) throws IOException {
int size; // using it for first line
int rows; // using it for second line
int cols; // using it for third line
// pass the path to the file as a parameter
FileReader fr =
new FileReader("input1.txt");
int i;
while ((i=fr.read()) != -1) {
System.out.print((char) i);
}
}
我正在尝试获取例外的输出,但是我从文件中获得了相同的行。我已经尝试使用System.out.print((char)i +“”);或System.out.print((char)i +'');但没有成功。有什么建议吗?
您可以使用BufferedReader
逐行读取文件。
BufferedReader
实际上,至少在Java 8上,“ System.out.print((char)i +”“);”应该工作正常。我刚刚尝试过,对我来说效果很好。您正在使用哪个Java版本?否则,您可以按照建议的@second尝试BufferedReader。
您可以执行以下操作:
public static void main(String[] args) throws IOException {
int size; // using it for first line
int rows; // using it for second line
int cols; // using it for third line
// pass the path to the file as a parameter
BufferedReader fr = new BufferedReader(
new FileReader("input1.txt")
);
// skipping 3 lines
fr.readLine();
fr.readLine();
fr.readLine();
String line = fr.readLine();
while (line != null) {
for (char c : line.toCharArray()) {
System.out.print(c + " ");
}
System.out.println();
line = fr.readLine();
}
}
输出:
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("demo.txt");
Scanner sc = new Scanner(file,StandardCharsets.UTF_8.name());
//Ignore first three lines
int count=0;
while(count<3){
sc.nextLine();
count++;
}
//Add space after each character in the remaining lines
while(sc.hasNext()) {
String line=sc.nextLine();
char []chars=line.toCharArray();
for(char c:chars)
System.out.printf("%c ",c);
System.out.println();
}
}
}