2017-10-10 79 views
0

在java中我可以做到這一點從字符串讀取和從輸入流讀取之間有什麼區別?

String sstream1 = 
     "as aasds 2 33\n" + 
     "this\n" + 
     "2.23\n"; 
InputStream stream = new ByteArrayInputStream(sstream1.getBytes()); 
Scanner cin = new Scanner(stream); 
Scanner cin2 = new Scanner(sstream1); 
String x1 = cin.next(); 
String x2 = cin.next(); 
int x3 = cin.nextInt(); 
int x4 = cin.nextInt(); 
String x5 = cin.next(); 
double x6 = cin.nextDouble(); 
Stream.of(x1, x2, x3, x4, x5, x6).forEach(o -> System.out.println(o)); 
x1 = cin2.next(); 
x2 = cin2.next(); 
x3 = cin2.nextInt(); 
x4 = cin2.nextInt(); 
x5 = cin2.next(); 
x6 = cin2.nextDouble(); 
Stream.of(x1, x2, x3, x4, x5, x6).forEach(o -> System.out.println(o)); 

我仍然得到同樣的結果

as 
aasds 
2 
33 
this 
2.23 
as 
aasds 
2 
33 
this 
2.23 

,所以我想知道什麼是使用這兩種方法之間的區別,有什麼優點和缺點對於每一個,因爲第二個更容易和更簡單,是否還有其他更好的方法來實現這一目標?

回答

0

向前伸直,最好

String sstream1 = ... // May contain Greek, Chinese, emoji, math symbols 
Scanner cin2 = new Scanner(sstream1); 

默認平臺編碼,來回轉換爲Unicode字符串。 特殊字符可能會出錯。不是跨平臺的。

InputStream stream = new ByteArrayInputStream(sstream1.getBytes()); 
Scanner cin = new Scanner(stream); 

明確的,跨平臺的,但兩次轉換。

InputStream stream = new ByteArrayInputStream(sstream1.getBytes(StandardCharsets.UTF_8)); 
Scanner cin = new Scanner(stream, "UTF-8"); 

請注意,System.out也使用默認的平臺字符集,這使測試代碼無法使用。但掃描僅適用於所有Unicode的第一個或最後一個代碼(使用Unicode的UTF-8)。

+0

我明白了,所以如果我只讀英文拉丁字符和數字,那麼我使用最簡單的形式沒有問題,非常感謝 –

0

InputStream是從資源獲取信息的原始方法。它在不執行任何翻譯的情況下逐字節地抓取數據。如果您正在讀取圖像數據或任何二進制文件,則這是要使用的流。

另一方面,當您使用String時,它是用於字符序列。您可以使用不同的字符編碼樣式並使用字符序列進行解碼。因此,如果您只讀取文本數據或字符,則可以使用String,但如果您使用的是圖像或任何二進制文件,則必須處理進一步的處理和編碼。