2013-10-22 92 views
1

我正在測試代碼,其中我必須從用戶輸入輸入,直到用戶輸入「停止」單詞,我必須將其寫入文件。我在代碼中出現錯誤。沒有合適的方法找到寫(字符串)

代碼:

import java.io.*; 
import java.util.*; 

public class fh1 

{ 
public static void main(String args[])throws IOException 

{ 

    FileOutputStream fout = new FileOutputStream("a.log"); 

    boolean status = true; 
    while (status) 
    { 
     System.out.println("Enter the word : "); 
     Scanner scan = new Scanner(System.in); 
     String word = scan.next(); 

     System.out.println(word); 

     if (word.equals("stop")) 
     { 
      status = false; 
     } 
     else 
     { 
      fout.write(word); 
     } 
    } 
    fout.close(); 
} 

} 

我收到以下錯誤:

fh1.java:28: error: no suitable method found for write(String) 
          fout.write(word); 
           ^
method FileOutputStream.write(byte[],int,int) is not applicable 
    (actual and formal argument lists differ in length) 
method FileOutputStream.write(byte[]) is not applicable 
    (actual argument String cannot be converted to byte[] by method invocation conversion) 
method FileOutputStream.write(int) is not applicable 
    (actual argument String cannot be converted to int by method invocation conversion) method FileOutputStream.write(int,boolean) is not applicable (actual and formal argument lists differ in length) 1 error 

這個錯誤是什麼意思,如何解決呢?

回答

3

,你可以嘗試像

fout.write(word.getBytes()); 
3

write功能需要字節數組作爲第一個參數。所以你應該將你的字符串轉換爲字節數組。您可以使用word.getBytes( 「UTF-8」)

3

嘗試

fout.write(word.getBytes()); 

write(byte[] b)

public void write(byte[] b) 
      throws IOException 
Writes b.length bytes from the specified byte array to this file output stream. 
Overrides: 
write in class OutputStream 
Parameters: 
b - the data. 
Throws: 
IOException - if an I/O error occurs. 
1
byte[] dataInBytes = word.getBytes(); 
fout.write(dataInBytes); 

轉寄此example

1

在處理字符(字符串)時,使用FileWriter作爲字符流。 也避免手動將字符串轉換爲字節。

public class Test14 

{ 
public static void main(String args[])throws IOException 

{ 

FileWriter fout = new FileWriter("a.log"); 

boolean status = true; 
while (status) 
{ 
    System.out.println("Enter the word : "); 
    Scanner scan = new Scanner(System.in); 
    String word = scan.next(); 

    System.out.println(word); 

    if (word.equals("stop")) 
    { 
     status = false; 
    } 
    else 
    { 
     fout.write(word); 
    } 
} 
fout.close(); 

}

}

它會奏效。 如果你只想寫日誌,使用java的記錄器api。

相關問題