java tostring 乱码_Java 里StringBuffer.toString总是乱码

各位好,这是我在网上看到的一个输入框提示的程序,我改了一下,content总是乱码,哪里的编码出问题了呢?我试着把content装成bytes[]在转成string还是乱码。

package com.bobliao;

import java.awt.BorderLayout;

import java.awt.event.KeyAdapter;

import javax.swing.JFrame;

import javax.swing.JList;

import javax.swing.JScrollPane;

import javax.swing.JTextField;

import javax.swing.SwingUtilities;

import org.apache.http.client.ClientProtocolException;

import java.awt.event.KeyEvent;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.net.URL;

import java.net.URLEncoder;

public class SuggestionTest extends JFrame {

private JTextField textInput=new JTextField();

private JList listSuggestions=new JList<>();

public SuggestionTest() {

super("SuggestionTest");

getContentPane().add(BorderLayout.NORTH,textInput);

getContentPane().add(BorderLayout.CENTER,

new JScrollPane(listSuggestions));

setSize(300,200);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);

this.textInput.addKeyListener(new KeyAdapter() {

@Override

public void keyReleased(KeyEvent e){

new Thread(() -> {

try{

String word=textInput.getText();

//word打印出来

System.out.println(word);

String[] suggestions=fetchSuggestionsFromBaidu(word);

SwingUtilities.invokeLater(() -> {

listSuggestions.removeAll();

listSuggestions.setListData(suggestions);

listSuggestions.updateUI();

});

}

catch (Exception ex) {

// TODO: handle exception

ex.printStackTrace();

}

}).start();

}

public String[] fetchSuggestionsFromBaidu(String word) throws

UnsupportedEncodingException,

ClientProtocolException,

IOException {

//获取建议词

String url="http://suggestion.baidu.com/su?wd="+URLEncoder.encode(word, "utf8");

URL urlReal=new URL(url);

InputStream stream=urlReal.openStream();

BufferedReader streamReader=new BufferedReader(new InputStreamReader(stream,"utf-8"));

StringBuffer stringBuffer=new StringBuffer();

String temp=null;

while((temp=streamReader.readLine())!=null){

stringBuffer.append(temp);

}

/*

* 这里的content总是会乱码啊*/

String content=new String(stringBuffer.toString());

System.out.println(content);

String[] suggestions=content.replaceAll(".*\\[(.*)\\].*", "$1").replaceAll("\"","").split(",");

return suggestions;

}

});

this.listSuggestions.addListSelectionListener(e -> {

textInput.setText(listSuggestions.getSelectedValue());

});

}

public static void main(String[] args) {

SwingUtilities.invokeLater(() ->{

new SuggestionTest();

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值