问题描述
我正在尝试将字符串存储在文件中。但是每次如果我在两个字符串之间放一个空格,它总是读取第一个字符串。
import java.util.*;
import java.io.*;
public class file_2 {
Scanner sc = new Scanner(system.in);
public void File() throws IOException {
FileOutputStream fout = new FileOutputStream("./file_2.txt",true);
// BufferedWriter bw=new BufferedWriter(fout);
System.out.println("Write a string:");
String s = sc.next();
char ch[] = s.tochararray();
System.out.println(ch);
for (int i = 0; i < s.length(); i++) {
fout.write(ch[i]);
}
fout.close();
// System.out.println("Length:"+length());
}
public static void main(String[] args) throws IOException {
file_2 file = new file_2();
file.File();
}
}
解决方法
扫描器使用分隔符模式将其输入分解为标记,默认情况下与空格匹配
后来:
扫描仪使用的默认空白分隔符由 Character.isWhitespace 识别
在 Java tutorial 中:
默认情况下,扫描仪使用空格来分隔标记。 (空白字符包括空格、制表符和行终止符。有关完整列表,请参阅 Character.isWhitespace 的文档。)
因此您可以使用 useDelimiter
更改分隔符或使用 nextLine
阅读整行