InputStream in = null 报空指针异常。

package com.infisight.hudmobile.obd.command;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;

//import awis.obd.io.ObdConnectThread;

public class ObdCommand extends Thread {

/**
 * @uml.property name="in"
 */
protected InputStream in = null;
/**
 * @uml.property name="out"
 */
protected OutputStream out = null;
/**
 * @uml.property name="buff"
 * @uml.associationEnd multiplicity="(0 -1)" elementType="java.lang.Byte"
 */
protected ArrayList<Byte> buff = null;
/**
 * @uml.property name="cmd"
 */
protected String cmd = null;
/**
 * @uml.property name="desc"
 */
protected String desc = null;
/**
 * @uml.property name="resType"
 */
protected String resType = null;
/**
 * @uml.property name="error"
 */
protected Exception error;
/**
 * @uml.property name="rawValue"
 */
protected Object rawValue = null;
/**
 * @uml.property name="data"
 * @uml.associationEnd 
 *                     qualifier="constant:java.lang.String java.lang.Double"
 */
protected HashMap<String, Object> data = null;
/**
 * @uml.property name="connectThread"
 * @uml.associationEnd inverse="cmds:awis.obd.io.ObdConnectThread"
 */
// protected ObdConnectThread connectThread = null;
/**
 * @uml.property name="impType"
 */
protected String impType = null;

public ObdCommand(String cmd, String desc, String resType, String impType) {
    this.cmd = cmd;
    this.desc = desc;
    this.resType = resType;
    this.buff = new ArrayList<Byte>();
    this.impType = impType;
}

// /**
// * @param thread
// * @uml.property name="connectThread"
// */
// public void setConnectThread(ObdConnectThread thread) {
// this.connectThread = thread;
// }
// public boolean isImperial() {
// if (connectThread != null && connectThread.getImperialUnits()) {
// return true;
// }
// return false;
// }

public ObdCommand(ObdCommand other) {
    this(other.cmd, other.desc, other.resType, other.impType);
}

public void setInputStream(InputStream in) {
    this.in = in;
}

public void setOutputStream(OutputStream out) {
    this.out = out;
}

public void run() {
    sendCmd(cmd);
    readResult();
}

public void setDataMap(HashMap<String, Object> data) {
    this.data = data;
}

protected void sendCmd(String cmd) {
    try {
        cmd += "\r\n";
        out.write(cmd.getBytes());
        out.flush();
    } catch (Exception e) {
        // TODO: handle exception
    }
}

protected void readResult() {
    byte c = 0;
    this.buff.clear();
    try {
        while ((char) (c = (byte) in.read()) != '>') {
            buff.add(c);
        }
    } catch (IOException e) {
    }
}

public String getResult() {
    return new String(getByteArray());
}

public byte[] getByteArray() {
    byte[] data = new byte[this.buff.size()];
    for (int i = 0; i < this.buff.size(); i++) {
        data[i] = this.buff.get(i);
    }
    return data;
}

public String formatResult(String ret) {
    String res = ret;
    String[] ress = res.split("\r");
    res = ress[0].replace(" ", "");
    return res;
}

/**
 * @return
 * @uml.property name="in"
 */
public InputStream getIn() {
    return in;
}

/**
 * @return
 * @uml.property name="out"
 */
public OutputStream getOut() {
    return out;
}

public ArrayList<Byte> getBuff() {
    return buff;
}

/**
 * @return
 * @uml.property name="cmd"
 */
public String getCmd() {
    return cmd;
}

/**
 * @return
 * @uml.property name="desc"
 */
public String getDesc() {
    return desc;
}

/**
 * @return
 * @uml.property name="resType"
 */
public String getResType() {
    return resType;
}

/**
 * @param e
 * @uml.property name="error"
 */
public void setError(Exception e) {
    error = e;
}

/**
 * @return
 * @uml.property name="error"
 */
public Exception getError() {
    return error;
}

/**
 * @return
 * @uml.property name="rawValue"
 */
public Object getRawValue() {
    return rawValue;
}

}
在package com.infisight.hudmobile.obd.command;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;

//import awis.obd.io.ObdConnectThread;

public class ObdCommand extends Thread {

/**
 * @uml.property name="in"
 */
protected InputStream in = null;
/**
 * @uml.property name="out"
 */
protected OutputStream out = null;
/**
 * @uml.property name="buff"
 * @uml.associationEnd multiplicity="(0 -1)" elementType="java.lang.Byte"
 */
protected ArrayList<Byte> buff = null;
/**
 * @uml.property name="cmd"
 */
protected String cmd = null;
/**
 * @uml.property name="desc"
 */
protected String desc = null;
/**
 * @uml.property name="resType"
 */
protected String resType = null;
/**
 * @uml.property name="error"
 */
protected Exception error;
/**
 * @uml.property name="rawValue"
 */
protected Object rawValue = null;
/**
 * @uml.property name="data"
 * @uml.associationEnd 
 *                     qualifier="constant:java.lang.String java.lang.Double"
 */
protected HashMap<String, Object> data = null;
/**
 * @uml.property name="connectThread"
 * @uml.associationEnd inverse="cmds:awis.obd.io.ObdConnectThread"
 */
// protected ObdConnectThread connectThread = null;
/**
 * @uml.property name="impType"
 */
protected String impType = null;

public ObdCommand(String cmd, String desc, String resType, String impType) {
    this.cmd = cmd;
    this.desc = desc;
    this.resType = resType;
    this.buff = new ArrayList<Byte>();
    this.impType = impType;
}

// /**
// * @param thread
// * @uml.property name="connectThread"
// */
// public void setConnectThread(ObdConnectThread thread) {
// this.connectThread = thread;
// }
// public boolean isImperial() {
// if (connectThread != null && connectThread.getImperialUnits()) {
// return true;
// }
// return false;
// }

public ObdCommand(ObdCommand other) {
    this(other.cmd, other.desc, other.resType, other.impType);
}

public void setInputStream(InputStream in) {
    this.in = in;
}

public void setOutputStream(OutputStream out) {
    this.out = out;
}

public void run() {
    sendCmd(cmd);
    readResult();
}

public void setDataMap(HashMap<String, Object> data) {
    this.data = data;
}

protected void sendCmd(String cmd) {
    try {
        cmd += "\r\n";
        out.write(cmd.getBytes());
        out.flush();
    } catch (Exception e) {
        // TODO: handle exception
    }
}

protected void readResult() {
    byte c = 0;
    this.buff.clear();
    try {
        while ((char) (c = (byte) in.read()) != '>') {
            buff.add(c);
        }
    } catch (IOException e) {
    }
}

public String getResult() {
    return new String(getByteArray());
}

public byte[] getByteArray() {
    byte[] data = new byte[this.buff.size()];
    for (int i = 0; i < this.buff.size(); i++) {
        data[i] = this.buff.get(i);
    }
    return data;
}

public String formatResult(String ret) {
    String res = ret;
    String[] ress = res.split("\r");
    res = ress[0].replace(" ", "");
    return res;
}

/**
 * @return
 * @uml.property name="in"
 */
public InputStream getIn() {
    return in;
}

/**
 * @return
 * @uml.property name="out"
 */
public OutputStream getOut() {
    return out;
}

public ArrayList<Byte> getBuff() {
    return buff;
}

/**
 * @return
 * @uml.property name="cmd"
 */
public String getCmd() {
    return cmd;
}

/**
 * @return
 * @uml.property name="desc"
 */
public String getDesc() {
    return desc;
}

/**
 * @return
 * @uml.property name="resType"
 */
public String getResType() {
    return resType;
}

/**
 * @param e
 * @uml.property name="error"
 */
public void setError(Exception e) {
    error = e;
}

/**
 * @return
 * @uml.property name="error"
 */
public Exception getError() {
    return error;
}

/**
 * @return
 * @uml.property name="rawValue"
 */
public Object getRawValue() {
    return rawValue;
}

}
在protected void readResult() {
byte c = 0;
this.buff.clear();
try {
while ((char) (c = (byte) in.read()) != '>') {
buff.add(c);
}
} catch (IOException e) {
}
}
中while ((char) (c = (byte) in.read()) != '>')这句一直报空指针异常,不知道是怎么回事。

3个回答

是不是你的in没有设置正确啊?给你个测试例子,在readResult方法中增加一个输出即可。

public static void main(String[] args) {
        ObdCommand obdCom = new ObdCommand("cmd", "desc", "resType", "impType");
        obdCom.setInputStream(System.in);
        obdCom.readResult();
    }

protected void readResult() {
        byte c = 0;
        this.buff.clear();
        try {
            while ((char) (c = (byte) inputStream.read()) != '>') {
                buff.add(c);
            }
            for (int i = 0; i < this.buff.size(); i++) {
                System.out.print(buff.get(i) + " ");
            }
        } catch (IOException e) {
        }
    } 

启动后在控制台输入we are ready>得到的结果如下;

we are ready>
119 101 32 97 114 101 32 114 101 97 100 121  

tongyi55555
JonsonJiao 回复android灬小菜鸟: 你这个问题是现在不知道你怎么赋值的,要不你贴一下你赋值的代码看看。再就是你自己测试下赋值的语句,看看赋值时是否传入的是null.
4 年多之前 回复
qq_22923235
android灬小菜鸟 那么请问要怎么样才能正确给InputStream赋值呢?
4 年多之前 回复
qq_22923235
android灬小菜鸟 还是有报空指针错误,Exception in thread "Thread-0" java.lang.NullPointerException at ObdCommand.readResult(ObdCommand.java:110) at ObdCommand.run(ObdCommand.java:92)
4 年多之前 回复

将对象这样赋值: InputStream in = null; 时,其实 in 并没有被正确的初始化,也就是分配空间。
后续使用时,如果直接给 in 赋值就会报错的。

91program
91program 回复android灬小菜鸟: 赋一个有效的值,如空格等,那怕是 “”
4 年多之前 回复
qq_22923235
android灬小菜鸟 那么请问要怎么样才能真确赋值呢。
4 年多之前 回复

在你的函数中判断下
if (in == null)
说明没有赋值

对于调用者,你需要传一个有效的输入流进来。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
求救啊安卓httpurlconnection.getinputstream报空指针异常
public Bitmap getBitmapFromURL(String urlString){ Bitmap bitmap ; InputStream is=null ; try { URL url=new URL(urlString); HttpURLConnection connection=(HttpURLConnection) url.openConnection(); is=new BufferedInputStream(connection.getInputStream()); bitmap=BitmapFactory.decodeStream(is); connection.disconnect(); return bitmap; } catch (java.io.IOException e) { e.printStackTrace(); }finally{ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } 这个类出了问题,问题出现在connection.getInputStream()
imageView获取图片空指针异常
通过URL获取图片时,然后在imageView中设置,结果系统给我报出空指针异常。 请高手帮忙解决一下,谢谢。 public class DetailsActivity extends Activity { ImageView thumbnail = (ImageView) findViewById(R.id.btnThumbnail); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detail); final Bundle extras = getIntent().getExtras(); String img = extras.getString("Thumbnail"); new DownloadImageTask((ImageView) findViewById(R.id.btnThumbnail)) .execute("http://mysite.com/images/" + img); } class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { public DownloadImageTask(ImageView bmImage) { thumbnail = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Log.e("URL",urldisplay); Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { thumbnail.setImageBitmap(result); } } }
空指针异常,初始化异常!求助!
``` public class JdbcUtils { private static Properties properties = null; static{ try { InputStream inp = JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties"); properties = new Properties(); properties.load(inp); } catch (IOException e) { throw new RuntimeException(e); } try { Class.forName(properties.getProperty("driverClassName")); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException{ return DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password")); } } public class AccountDao { public void updateBalance(Connection con,String name,double balance){ try { String sql = "update account set balance=balance+? where name=?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(2, name); pstmt.setDouble(3, balance); pstmt.executeUpdate(); } catch (Exception e) { throw new RuntimeException(e); } } } public class Demo1 { public void transfer_account(String from,String to,double money) { Connection con =null; try { con=JdbcUtils.getConnection(); System.out.println("falt"); con.setAutoCommit(false); AccountDao dao = new AccountDao(); dao.updateBalance(con,from, -money); dao.updateBalance(con,to, money); con.commit(); con.close(); } catch (Exception e) { try { con.rollback(); con.close(); } catch (SQLException e1) { throw new RuntimeException(e); } }finally{ if(con!=null) try { con.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } @Test public void fun2() { transfer_account("zs", "ls", 100); } } ``` 测试时出现初始化异常和空指针异常,实在找不到问题在哪……
Volley请求数据遇到问题,显示空指针
我用Volley请求数据传给了,而且Log也有数据,但是当我想用settext()把数据传进去,却显示空指针,而我要是把settext放在点击事件里面,就可以显示处理,求助这是怎么回事 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); getDataFromNet(); initData(); } private void initData() { //tv.setMovementMethod(ScrollingMovementMethod.getInstance());// 滚动 tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Spanned spanned = Html.fromHtml(html, new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { InputStream is = null; try { is = (InputStream) new URL(source).getContent(); Drawable d = Drawable.createFromStream(is, null); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); is.close(); return d; } catch (Exception e) { return null; } } } , null); tv.setText(spanned); } } ); } private void initView() { tv = (TextView) findViewById(R.id.tv); } private void getDataFromNet() { RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String s) { Log.i("aa", "post请求成功" + s); Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show(); /** * 解析数据 */ processData(s); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.i("aa", "post请求失败" + volleyError.toString()); Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put("contentid", "567210bd5d774358778b4c51"); map.put("client", "2"); return map; } }; requestQueue.add(request); } private Bean.DData ddata; private void processData(String s) { final Bean data = Bean.getData(s); ddata = data.data; html = ddata.html; } } 这样是没问题的。 public class MainActivity extends AppCompatActivity { private TextView tv; private String url = "http://api2.pianke.me/article/info"; String html; Spanned spanned; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); getDataFromNet(); initData(); tv.setText(spanned); } private void initData() { //tv.setMovementMethod(ScrollingMovementMethod.getInstance());// 滚动 spanned = Html.fromHtml(html, new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { InputStream is = null; try { is = (InputStream) new URL(source).getContent(); Drawable d = Drawable.createFromStream(is, null); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); is.close(); return d; } catch (Exception e) { return null; } } } , null); } private void initView() { tv = (TextView) findViewById(R.id.tv); } private void getDataFromNet() { RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String s) { Log.i("aa", "post请求成功" + s); Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show(); /** * 解析数据 */ processData(s); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.i("aa", "post请求失败" + volleyError.toString()); Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put("contentid", "567210bd5d774358778b4c51"); map.put("client", "2"); return map; } }; requestQueue.add(request); } private Bean.DData ddata; private void processData(String s) { final Bean data = Bean.getData(s); ddata = data.data; html = ddata.html; } } 但是这样就报空指针,请教各位
用基于lucene的web项目实现的简单的搜索引擎,出现线程抛出的空指针异。
这个项目一共有五个java类,一个search.jsp,一个web.xml。问题在于在eclipse上加入tomcat后,在浏览器输入地址就会报下面截图上的错误,我觉得可能是建立索引和找索引有问题,但我不太了解这是怎么回事还有该怎么解决: 问题截图: ![图片说明](https://img-ask.csdn.net/upload/201506/05/1433484723_587779.jpg) ![图片说明](https://img-ask.csdn.net/upload/201506/05/1433484737_48592.jpg) 代码全部: ``` package sample.dw.paper.lucene.servlet; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import sample.dw.paper.lucene.search.SearchManager; public class SearchController extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{ doPost(request, response); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{ // String searchWord = request.getParameter("searchWord"); String searchWord = toChinese(request.getParameter("searchWord")); SearchManager searchManager = new SearchManager(searchWord); List searchResult = null; searchResult = searchManager.search(); RequestDispatcher dispatcher = request.getRequestDispatcher("search.jsp"); request.setAttribute("searchResult", searchResult); dispatcher.forward(request,response); } public static String toChinese(String strvalue){ try { if(strvalue==null){ return null; }else{ strvalue = new String(strvalue.getBytes("ISO-8859-1"),"UTF-8"); return strvalue; } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return null; } } } ``` ``` package sample.dw.paper.lucene.search; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import sample.dw.paper.lucene.index.IndexManager; public class SearchManager { private String searchWord; private IndexManager indexManager; private Analyzer analyzer; private IndexSearcher indexSearcher; public SearchManager(String serachWord){ this.searchWord = serachWord; this.indexManager = new IndexManager(); this.analyzer = new StandardAnalyzer(); } public List search(){ List searchResult = new ArrayList(); if (false == indexManager.ifIndexExist()) { try { if (false == indexManager.createIndex()) { return searchResult; } } catch (IOException e) { // TODO: handle exception e.printStackTrace(); return searchResult; } } indexSearcher = null; try { indexSearcher = new IndexSearcher(indexManager.getIndexDir()); } catch (IOException e) { // TODO: handle exceptio e.printStackTrace(); } QueryParser queryParser = new QueryParser( "content",analyzer); Query query = null; try { query = queryParser.parse(searchWord); } catch (ParseException e) { // TODO: handle exception e.printStackTrace(); } if( null !=query && null != indexSearcher){ try { Hits hits=indexSearcher.search(query); for(int i=0; i<hits.length();i++){ SearchResultBean resultBean = new SearchResultBean(); resultBean.setHtmlPath(hits.doc(i).get("path")); resultBean.setHtmlTitle(hits.doc(i).get("title")); searchResult.add(resultBean); } } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } return searchResult; } } ``` ``` package sample.dw.paper.lucene.search; public class SearchResultBean { private String htmlPath; private String htmlTitle; public String getHtmlPath() { int startPos = htmlPath.indexOf("mirror")+6; String url=htmlPath; url = url.substring(startPos); url = url.replaceAll("\\\\","/"); htmlPath = "http:"+url; return htmlPath; } public void setHtmlPath(String htmlPath) { this.htmlPath = htmlPath; } public String getHtmlTitle() { return htmlTitle; } public void setHtmlTitle(String htmlTitle) { this.htmlTitle = htmlTitle; } } ``` ``` package sample.dw.paper.lucene.index; import java.io.File; import java.io.IOException; import java.io.Reader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import sample.dw.paper.lucene.util.HTMLDocParser; public class IndexManager { public final String dataDir = "C:\\Users\\yang\\workspace\\graduation_project_heritrix\\jobs"+"\\csdn-20150423124021677\\mirror"; public final String indexDir ="C:\\indexDir"; public void ccreateIndex(File file,IndexWriter indexWriter)throws IOException{ if(file.isDirectory()){ File [] files =file.listFiles(); for(int i=0 ; i<files.length; i++){ ccreateIndex(files[i],indexWriter); } }else if(file.getAbsolutePath().endsWith(".html") || file.getAbsolutePath().endsWith(".htm")){ String htmlPath = file.getAbsolutePath(); addDocument(htmlPath,indexWriter); } } public boolean createIndex() throws IOException{ if(true == ifIndexExist()){ return true; } File dir = new File(dataDir); if(!dir.exists()){ return false; } File[] htmls = dir.listFiles(); Directory fsDirectory = FSDirectory.getDirectory(indexDir, true); Analyzer analyzer = new StandardAnalyzer(); IndexWriter indexWriter = new IndexWriter(fsDirectory, analyzer, true); for(int i = 0; i < htmls.length; i++){ String htmlPath = htmls[i].getAbsolutePath(); if(htmlPath.endsWith(".html") || htmlPath.endsWith(".htm")){ addDocument(htmlPath, indexWriter); } } indexWriter.optimize(); indexWriter.close(); return true; // Directory fsDirectory = FSDirectory.getDirectory(indexDir, true); // Analyzer analyzer = new StandardAnalyzer(); // IndexWriter indexWriter = new IndexWriter(fsDirectory,analyzer,true); // ccreateIndex(filee,indexWriter); // // indexWriter.close(); // return true; } public void addDocument(String htmlPath,IndexWriter indexWriter) { /*HTMLDocParser htmlParser = new HTMLDocParser(htmlPath); String path = htmlParser.getPath(); String title = htmlParser.getTitle(); String content = htmlParser.getContent(); // Document document = new Document(); document.add(new Field(title,new StringReader(content))); indexWriter.addDocument(document);*/ HTMLDocParser htmlParser = new HTMLDocParser(htmlPath); String path = htmlParser.getPath(); String title = htmlParser.getTitle(); Reader content = htmlParser.getContent(); Document document = new Document(); document.add(new Field("path",path,Field.Store.YES,Field.Index.NO)); document.add(new Field("title",title,Field.Store.YES,Field.Index.TOKENIZED)); document.add(new Field("content",content)); try { indexWriter.addDocument(document); } catch (IOException e) { e.printStackTrace(); } } public boolean ifIndexExist(){ File directory = new File(indexDir); if(0 < directory.listFiles().length){ return true; }else{ return false; } } public String getDataDir(){ return this.dataDir; } public String getIndexDir(){ return this.indexDir; } } ``` ``` package sample.dw.paper.lucene.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import org.apache.lucene.demo.html.HTMLParser; public class HTMLDocParser { private String htmlPath; private HTMLParser htmlParser; public HTMLDocParser(String htmlPath){ this.htmlPath = htmlPath; initHtmlParser(); } private void initHtmlParser(){ InputStream inputStream = null; try { inputStream = new FileInputStream(htmlPath); } catch (FileNotFoundException e) { e.printStackTrace(); } if(null != inputStream){ try { htmlParser = new HTMLParser(new InputStreamReader(inputStream, "utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } public String getTitle(){ if(null != htmlParser){ try { return htmlParser.getTitle(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } return ""; } public Reader getContent(){ if(null != htmlParser){ try { return htmlParser.getReader(); } catch (IOException e) { e.printStackTrace(); } } return null; } public String getPath(){ return this.htmlPath; } } ```
hdfs中视频文件的读取
我在hdfs中上传了一个视频文件,现在想读取视频文件的一些信息 String uri = "hdfs://master:9000/input/video1.mp4"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); }finally { } File source = null; inputstreamtofile(in,source); Encoder encoder = new Encoder(); try { MultimediaInfo m = encoder.getInfo(source); long ls = m.getDuration(); System.out.println("此视频时长为:"+ls/60000+"分"+(ls/000)/1000+"秒!"); } catch(Exception e) { e.printStackTrace(); } 其中 inputstreamtofile是想将数据流转化为File public static void inputstreamtofile(InputStream in,File sor) throws IOException{ OutputStream os = new FileOutputStream(sor); int bytesRead = 0; byte[] buffer = new byte[19230720]; while ((bytesRead = in.read(buffer, 0, 19230720)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); in.close(); } 但是运行时候会有空指针异常 Exception in thread "main" java.lang.NullPointerException at java.io.FileOutputStream.<init>(FileOutputStream.java:212) at java.io.FileOutputStream.<init>(FileOutputStream.java:171) at mapreduce.readvideoinfo.inputstreamtofile(readvideoinfo.java:20) at mapreduce.readvideoinfo.main(readvideoinfo.java:40) 这个应该怎么改呢
安卓与Servlet交互,空指针
客户端关键源码如下: AsyncHttpClient add=new AsyncHttpClient(); add.addHeader("charset", HTTP.UTF_8); add.addHeader("Content-Type", "text/plain"); price=pri.getText().toString(); RequestParams params=new RequestParams(); RequestParams picparms=new RequestParams(); //截取图片名称 String upic=realPath.substring(realPath.lastIndexOf("/")+1, realPath.length()); File pic=new File(realPath); System.out.println(upic); params.add("type", "mobile"); params.add("model", model); params.add("brand", brand); params.add("price", "1200"); params.add("picPath", upic); //图片上传 try { picparms.put("pic", new PhotoUpload().Upload(realPath)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(">>>>>>>>>>图片大小为:"+pic.length()); System.out.println("基本信息:"+params.toString()); add.get(URL, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) { // TODO Auto-generated method stub System.out.println("服务器连接成功"); if(arg0==200) { boolean b = Boolean.valueOf(new String(arg2)); if(b) { Toast.makeText(UpdateCom.this, "图片上传成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(UpdateCom.this, "图片上传失败", Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) { // TODO Auto-generated method stub System.out.println("服务器连接失败"); } }); add.post(URL, picparms, new AsyncHttpResponseHandler() { @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) { // TODO Auto-generated method stub System.out.println("服务器连接成功"); if(arg0==200) { boolean b = Boolean.valueOf(new String(arg2)); if(b) { Toast.makeText(UpdateCom.this, "基本信息上传成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(UpdateCom.this, "基本信息上传失败", Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) { // TODO Auto-generated method stub System.out.println("服务器连接失败"); } //显示上传进度 public void onProgress(int bytesWritten, int totalSize) { // TODO Auto-generated method stub super.onProgress(bytesWritten, totalSize); int count = (int) ((bytesWritten * 1.0 / totalSize) * 100); // 上传进度显示 progress.setProgress(count); Log.e("上传 Progress>>>>>", bytesWritten + " / " + totalSize); } }); break; default: break; } } 为什么有post和get呢,就是楼主要问的,应为post传上去,更本就拿不出来,而get不能传图片等大文件;所以就有了两个parms,对了,我在这里用到了AsyncHttpClient; 服务器关键代码为: package package_for_ordinary_person; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.RequestContext; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import com.beans.CompetGoods; import com.dao_for_interface.CompGoodsDao; /** * Servlet implementation class AddComproduct */ @WebServlet("/AddComproduct") public class AddComproduct extends HttpServlet { boolean flag; private static final long serialVersionUID = 1L; CompGoodsDao cgd = new CompGoodsDao(); CompetGoods cgoods; java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis()); public String brand,model,picPath; /** * @see HttpServlet#HttpServlet() */ public AddComproduct() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @SuppressWarnings("resource") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String type = request.getParameter("type"); brand = request.getParameter("brand"); model = request.getParameter("model"); String price = request.getParameter("price"); picPath = request.getParameter("picPath"); System.out.println(type + brand + model + price+picPath); cgoods = new CompetGoods(); cgoods.setType(type); cgoods.setBrand(brand); cgoods.setModel(model); cgoods.setCprice(price); cgoods.setUploadDate(currentDate); if (cgd.upload(cgoods)) { flag = true; } else { flag = false; } response.setContentType("text/plain,charset=UTF-8"); PrintWriter out = response.getWriter(); out.print(flag); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub cgoods=new CompetGoods(); System.out.println(">>>>>" + request.getContentLength()); InputStream is = request.getInputStream(); // String picdate=request.getParameter("pic"); // System.out.println(">>>>>" + picdate.length()); File file=new File("//usr//local//ImageFromClient//"+picPath); if (!file.exists()) { try { System.out.println("文件不存在,正在创建.路径为" + file); file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileOutputStream fos1 = new FileOutputStream(file); // fos1.write(new sun.misc.BASE64Decoder().decodeBuffer(is)); int i = 0; while ((i = is.read()) != -1) { fos1.write(i); } fos1.close(); is.close(); // 图片保存并入库 /*FileOutputStream fos = null; File file = new File("//usr//local//ImageFromClient//" + picPath); if (!file.exists()) { try { System.out.println("文件不存在,正在创建.路径为" + file); file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } fos = new FileOutputStream(file);*/ /* * try { //写入的是字节流 //通过解码之后直接生成图片 //picPath存储的是图片文件字节 fos.write(new * sun.misc.BASE64Decoder().decodeBuffer(picPath)); * System.out.println("成功写入" + file); } catch (IOException e) { // TODO * Auto-generated catch block e.printStackTrace(); } */ cgoods.setBrand(brand); cgoods.setModel(model); cgoods.setCpicPath(file.toString()); if (cgd.updatecom(cgoods)) { flag = true; } else { flag = false; } response.setContentType("text/plain,charset=UTF-8"); PrintWriter out = response.getWriter(); out.print(flag); } } 另外补充,post方法的request是可以打印出来大小的,就是取不出来.
JDBC使用反射读取properties文件出错
使用反射获取类加载器来读取properties文件出现空指针异常,可以使用直接使用输入流读取properties文件,为什么教学视频中却可以使用反射?另外问下怎么在PC端提问,不是论坛发帖,单纯悬赏C币提问,我都是在手机上提,电脑上修改 @Test public void getConnection() throws Exception { /* * 读取配置文件来获取数据库连接 */ Properties properties = new Properties(); String driverClass = null; String jdbcUrl = null; String user = null; String password = null; InputStream in = this.getClass().getClassLoader().getResourceAsStream("C:/Java/WprkSpace/JDBC/jdbc.properties"); properties.load(in); driverClass = properties.getProperty("driver"); jdbcUrl = properties.getProperty("jdbcUrl"); user = properties.getProperty("user"); password = properties.getProperty("password"); Driver driver = (Driver) Class.forName(driverClass).newInstance(); properties.put("user", user); properties.put("password", password); Connection connerction = driver.connect(jdbcUrl, properties); System.out.println( connerction); in.close(); } ![图片说明](https://img-ask.csdn.net/upload/201607/14/1468511565_146162.png) ![图片说明](https://img-ask.csdn.net/upload/201607/14/1468511578_461313.png) ![图片说明](https://img-ask.csdn.net/upload/201607/14/1468511589_915518.png) ![图片说明](https://img-ask.csdn.net/upload/201607/14/1468511603_770079.png)
spring的@Component组件无法注入?
需要注入的类 ``` @Component public class WXConfig implements com.github.wxpay.sdk.WXPayConfig { /** * 服务器地址 */ @Value("${weChat.domain}") private String domain; /** * 商户Id */ @Value("${weChat.mchId}") private String mchId; /** * 支付key */ @Value("${weChat.key}") private String key; /** * appid */ @Value("${weChat.appId}") private String appId; /** * appSecret */ @Value("${weChat.appSecret}") private String appSecret; @Override public String getAppID() { return appId; } @Override public String getMchID() { return mchId; } @Override public String getKey() { return key; } @Override public InputStream getCertStream() { return null; } /** * 连接超时时间 * * @return */ @Override public int getHttpConnectTimeoutMs() { return 10 * 1000; } /** * 读取超时时间 * * @return */ @Override public int getHttpReadTimeoutMs() { return 10 * 1000; } public String getMchId() { return mchId; } public String getAppSecret() { return appSecret; } public String getGrantType() { return "authorization_code"; } /** * 回调地址 */ public String getNotifyURL() { return this.domain + "/order/wxPayUnifiedNotify"; } } ``` 调用的类 ``` /** * 微信相关 * * @author tangchao */ @Component public class WxUtil { @Autowired private WXConfig wxConfig; private final Logger LOG = LoggerFactory.getLogger(this.getClass()); /** * 用户登录 * * @param code 前端登录code * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据 * @param iv 加密算法的初始向量 * @return 返回用户信息 nickName,avatarUrl,gender,unionid,city,province,country,openid * @throws Exception */ public JSONObject loginByWeixin(String code, String encryptedData, String iv) throws Exception { WxUtil wxUtil = new WxUtil(); //根据code去调用接口获取用户openid和session_key JSONObject json = wxUtil.getSessionKeyAndOpenid(code); System.out.println("返回过来的json数据:" + json.toString()); //会话秘钥 String sessionkey = json.get("session_key").toString(); //用户唯一标识 String openid = json.get("openid").toString(); //拿到用户session_key和用户敏感数据进行解密,拿到用户信息。 String decrypts = wxUtil.decrypt(encryptedData, sessionkey, iv, "utf-8"); JSONObject jsons = JSONObject.parseObject(decrypts); jsons.put("openid", openid); return jsons; } } ``` wxConfig报空指针,为什么?
java web 多线程下载文件的问题。
**当我开启多线程下载文件时,outputstream.write 报 空指针 错误。 大佬们帮我看看 ** ``` ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute( new Runnable() { @Override public void run() { String path=System.getProperty("catalina.home")+"/webapps/uploadFiles/njhb/areaFiles/南京市/"+fileName; final File file = new File(path); if(!file.exists()){ System.out.println("文件不存在"); //response.setHeader("content-type", "text/html;charset=UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = null; try { writer = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } writer.write("文件不存在!"); return; } response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName="+ encodingFileName(fileName)); response.setHeader("Set-Cookie", "fileDownload=true; path=/;" + "attachment;fileName=" + encodingFileName(fileName)); try { //打开本地文件流 InputStream inputStream = new FileInputStream(file); //激活下载操作 OutputStream outputStream = response.getOutputStream(); //循环写入输出流 每次读取2048 一直读完 byte[] b = new byte[2048]; int length; int count=0; while ((length = inputStream.read(b)) > 0) { System.out.println("b: "+b+" length: "+length); outputStream.write(b, 0, length); count++; } // 这里主要关闭。 outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); logg.info("文件下载终止!!!"); } } } ); ``` 下面是报错信息!! ![图片说明](https://img-ask.csdn.net/upload/201905/30/1559211144_987376.jpg)
用Java程序模拟Tomcat报错
写了一个Java模拟Tomcat后用QQ浏览器、火狐、谷歌测试一会儿能用,一会儿报空指针异常,一会又报Connection reset是怎么回事就是这时好时坏代码没动过package com.briup.server; import java.net.ServerSocket; import java.net.Socket; import java.io.*; /** * web服务器项目,此项目工作在服务器端,功能: 1、接受请求 2、分析请求 3、给出响应 * * @author wkx * */ public class ServerMain { public static void main(String[] args) { try { new ServerMain().receive(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void receive() throws IOException { System.out.println("服务器启动。。。"); // 创建ServerSocket对象 ServerSocket server = new ServerSocket(8888); while (true) { // 接受客户端的socket Socket socket = server.accept(); // 获取socket输入流 InputStream is = socket.getInputStream(); // 将字节流封装成字符流方便读取 BufferedReader br = new BufferedReader(new InputStreamReader(is)); // 客户端的请求信息 // String line = null; // while ((line = br.readLine()) != null) { // System.out.println(line); // } // 分析请求 String line = br.readLine(); String[] str = line.split(" "); String url = str[1]; File file = new File("D:\\java\\eclipse\\workspace\\Tomcat_JD1719_1\\my", url); // 获得socket输出流 OutputStream os = socket.getOutputStream(); PrintStream ps = new PrintStream(os, true); if (file.exists()) { // 响应行 ps.println("HTTP/1.1 200 ok"); // 响应头 // 空行 ps.println(); // 响应体 FileInputStream fis = new FileInputStream(file); int len = 0; byte b[] = new byte[1024]; while ((len = fis.read(b)) != -1) { ps.write(b, 0, len); } fis.close(); socket.close(); } else { // 响应行 ps.println("HTTP/1.1 404 not found"); // 响应头 // 空行 ps.println(); // 响应体 File errorfile = new File("D:\\java\\eclipse\\workspace\\Tomcat_JD1719_1\\my", "\\error.txt"); FileInputStream fis = new FileInputStream(errorfile); int len = 0; byte b[] = new byte[1024]; while ((len = fis.read(b)) != -1) { ps.write(b, 0, len); } fis.close(); socket.close(); } } } } ![图片说明](https://img-ask.csdn.net/upload/201710/26/1509000543_719901.png) ![图片说明](https://img-ask.csdn.net/upload/201710/26/1509000575_994926.png) ![图片说明](https://img-ask.csdn.net/upload/201710/26/1509000593_296478.png)
jdbc 测试问题(使用JUtil4)
``` package com.java; import java.io.InputStream; import java.sql.Connection; import java.sql.Driver; import java.util.Properties; import org.junit.Test; public class javaTest { public Connection getConnection() throws Exception { String driverClass = null; String jdbcUrl = null; String user = null; String password = null; InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(in); driverClass = properties.getProperty("driver"); jdbcUrl = properties.getProperty("jdbcUrl"); user = properties.getProperty("user"); password = properties.getProperty("password"); Driver driver = (Driver) Class.forName(driverClass).newInstance(); Properties info = new Properties(); info.put("user",user); info.put("password",password); Connection connection = driver.connect(jdbcUrl,info); return connection; } @Test public void testGetConnection() throws Exception { System.out.println(getConnection()); } } ``` java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Properties.java:434) at java.util.Properties.load0(Properties.java:353) at java.util.Properties.load(Properties.java:341) at com.java.javaTest.getConnection(javaTest.java:23) at com.java.javaTest.testGetConnection(javaTest.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 出现了空指针异常 是怎么回事呢?查了好多资料都没有解决了 这个应该不是JUtil4兼容问题吧? ![图片说明](https://img-ask.csdn.net/upload/201705/24/1495625093_432731.jpg) 这个问题困扰我好久了 自己弄了半天也没有解决了 希望大神们可以帮我,指点我一下。
struts1 多个文件下载问题
下载的action代码如下: [code="java"] public ActionForward getAttachments(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { long id = (Long) request.getSession().getAttribute("mid"); UserInfo ui = (UserInfo) request.getSession().getAttribute("userinfo"); Attachment[] atts = mailService.getAttachments(ui, id); response.reset(); for (int i = 0; i < atts.length; i++) { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(atts[i].getFileName(), "utf-8")); InputStream fis = atts[i].buildInputStream(); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); OutputStream toClient = new BufferedOutputStream(response .getOutputStream()); String type = atts[i].getFileName(); int n = 0; while (n != -1) { n = type.indexOf("."); type = type.substring(n + 1); } if (type.toUpperCase().equals("DOC")) response.setContentType("application/msword"); else response.setContentType("application/x-msdownload"); toClient.write(buffer); toClient.flush(); toClient.close(); } return null; } [/code] 每一个Attachment对应的一个附件: [code="java"] public class Attachment implements Serializable { private static final long serialVersionUID = 7853572746765662317L; private String fileName; private byte[] data; public Attachment() { } public Attachment(String fileName, byte[] data) { this.fileName = fileName; this.data = data; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public InputStream buildInputStream() { return new ByteArrayInputStream(data); } } [/code] 有多个文件下载的时候,[color=red]只能下载第一个,其余的就不弹出对话框下载[/color]了,另外在下载的时候[color=red]用IE自带的另存为可以下载,但是出来迅雷的时候不能下载,总是报long id = (Long) request.getSession().getAttribute("mid");空指针异常[/color]。这是什么原因呢?谢谢! [b]问题补充:[/b] 上传没有问题。 [b]问题补充:[/b] 迅雷中[color=darkred]另存为为 taxmail.do,显示所需空间为0k,当报空指针异常的时候,它会一遍遍的产生多次[/color],另外,我为什么[color=red]不能下载多个文件呢?[/color]我的到的是多个文件,那个地方写错了么? [b]问题补充:[/b] 我跟踪调试了一下,确实循环了三次,但是只下载了第一个,web难道不能这样一次下载多个文件?
求助:netty 4.x服务器端出现CLOSE_WAIT的问题
**1.主题:**我最近用netty4.x 做了一个app服务端,在部署到服务器上之后出现了很多close_wait 状态的TCP连接 ,导致服务端卡住,不能再接收新的连接,但是换回本地测试又不会出现这样的问题。 **2.详细描述:** 1)当服务端出现卡住的情况时,使用netstat -ano 命令可以看到服务器的连接状态还是established,抓包也能看到客户端仍然在正常发送数据包,但是服务器只是回应了一个ACK(此时服务端已经卡住,控制台没有任何动作,也没有日志记录)。 ![图片说明](https://img-ask.csdn.net/upload/201807/12/1531381902_865010.jpg) 下面那一个是心跳包。 只要客户端不关闭连接,一直是established,直到客户端断开连接后,就变成了close_wait。只有一次服务端从这种“卡死”状态恢复,并且打印了日志(比如"用户的断开连接")。 一开始我以为是某一步阻塞,而导致了这个情况,于是又用jstack 命令查看了阻塞状态,转下节, 2) 显示结果: ![图片说明](https://img-ask.csdn.net/upload/201807/12/1531382616_657392.png) 3)在查看官方的使用手册和《netty 实战》中,有提到入站出站消息需要使用ReferenceCountUtil.release()进行,手动释放,但我的编解码器用的分别是ByteToMessageDecoder和MessageToByteEncoder,源码上这两个都进行了Bytebuf的释放处理, 所以问题应该不是出在这里吧..... 以下是编解码器的部分代码: encoder ``` @Override protected void encode(ChannelHandlerContext ctx, YingHeMessage msg, ByteBuf out) throws Exception { checkMsg(msg);// not null int type = msg.getProtoId(); int contentLength = msg.getContentLength(); String body = msg.getBody(); out.writeInt(type); out.writeInt(contentLength); out.writeBytes(body.getBytes(Charset.forName("UTF-8"))); } ``` decoder ``` //int+int private static final int HEADER_SIZE = 8; private static final int LEAST_SIZE = 4; private static final Logger LOG = LoggerFactory.getLogger(YingHeMessageDecoder.class); @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { in.markReaderIndex();//第一次mark int readable = in.readableBytes(); LOG.info("check:{}", in.readableBytes() < HEADER_SIZE); LOG.info("readable:{}", readable); if (in.readableBytes() < HEADER_SIZE) {//消息过小回滚指针,不作处理 LOG.warn(">>>可读字节数小于头部长度!"); LOG.info("before reset:{}", in.readerIndex()); in.resetReaderIndex(); LOG.info("after reset:{}", in.readerIndex()); return; } //读取消息类型 int type = in.readInt(); int contentLength = in.readInt(); LOG.info("type:{},contentLength:{}", type, contentLength); in.markReaderIndex();//第二次mark int readable2 = in.readableBytes(); if (readable2 < contentLength) { LOG.error("内容长度错误!length=" + contentLength); in.resetReaderIndex();//重设readerIndex LOG.info("重设,当前readerIndex:" + in.readerIndex()); return; } //读取内容 ByteBuf buf = in.readBytes(contentLength); byte[] content = new byte[buf.readableBytes()]; buf.readBytes(content); String body = new String(content, "UTF-8"); YingHeMessage message = new YingHeMessage(type, contentLength, body); out.add(message); } ``` 下面是服务器启动类的配置: ``` public void run() throws Exception { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(5); try { ServerBootstrap b = new ServerBootstrap(); b.group(boss, worker) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true) .handler(new LoggingHandler(LogLevel.DEBUG)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new LengthFieldBasedFrameDecoder(MAX_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP)) .addLast(new ReadTimeoutHandler(60)) .addLast(new YingHeMessageDecoder()) .addLast(new YingHeMessageEncoder()) .addLast(new ServerHandlerInitializer()) .addLast(new Zenith()); } }); Properties properties = new Properties(); InputStream in = YingHeServer.class.getClassLoader().getResourceAsStream("net.properties"); properties.load(in); Integer port = Integer.valueOf(properties.getProperty("port")); ChannelFuture f = b.bind(port).sync(); LOG.info("服务器启动,绑定端口:" + port); DiscardProcessorUtil.init(); System.out.println(">>>flush all:" + RedisConnector.getConnector().flushAll()); LOG.info(">>>redis connect test:ping---received:{}", RedisConnector.getConnector().ping()); f.channel().closeFuture().sync(); } catch (IOException e) { e.printStackTrace(); } finally { //清除 LOG.info("优雅退出..."); boss.shutdownGracefully(); worker.shutdownGracefully(); ChannelGroups.clear(); } } ``` 4)其他补充说明: 服务器为windows server 2012r; 客户端使用的C sharp编写; 服务端使用了Netty 4.1.26.Final,Mybatis,Spring,fastjson,redis(缓存),c3p0(连接池); 本地测试不会出现这种情况! 40c币奉上,还请各位大牛不吝赐教,救小弟于水火啊!
detectMultiScale函数一加入就会崩溃,程序自动停止但不报错,求解!
根据教程制作了人脸识别的程序,但是detectMultiScale无法正常运行,一旦加入就会使程序停止,求大神你帮帮我,很急! 初始化模型 ``` public void initializeOpenCVDependencies() { try { // Copy the resource into a temp file so OpenCV can load it InputStream is = getResources().openRawResource(R.raw.lbpcascade_frontalface_improved); File cascadeDir = getDir("cascade", Context.MODE_PRIVATE); File mCascadeFile = new File(cascadeDir.getAbsoluteFile(), "lbpcascade_frontalface_improved.xml"); FileOutputStream os = new FileOutputStream(mCascadeFile); byte[] buffer = new byte[4096]; int bytesRead=0; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); os.close(); // Load the cascade classifier CascadeClassifier detectface = new CascadeClassifier(mCascadeFile.getAbsolutePath()); // detectface.load("lbpcascade_frontalface_improved.xml"); } catch (Exception e) { Log.e("OpenCVActivity", "Error loading cascade", e); } ``` 检测段 ``` public void procSrc2Gray(){ Mat rgbMat = new Mat(); Mat grayMat = new Mat(); Mat guess= new Mat(); Mat canny=new Mat(); Mat lines=new Mat(); MatOfRect car=new MatOfRect(); srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a); grayBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.RGB_565); Utils.bitmapToMat(srcBitmap, rgbMat);//convert original bitmap to Mat, R G B. Imgproc.cvtColor(rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);//rgbMat to gray grayMat MatOfRect cars=new MatOfRect(); detectface.detectMultiScale(grayMat,car,1.1,3,0,new Size(50,50),new Size()); ``` -------------- 补充问题日志 ``` Process: com.example.myapplication, PID: 3254 java.lang.NullPointerException: Attempt to invoke virtual method 'void org.opencv.objdetect.CascadeClassifier.detectMultiScale(org.opencv.core.Mat, org.opencv.core.MatOfRect, double, int, int, org.opencv.core.Size, org.opencv.core.Size)' on a null object reference at com.example.myapplication.MainActivity.procSrc2Gray(MainActivity.java:139) at com.example.myapplication.MainActivity$ProcessClickListener.onClick(MainActivity.java:188) at android.view.View.performClick(View.java:4780) at android.view.View$PerformClick.run(View.java:19866) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) ```不知道为什么这个就变成空指针了=。=
求助,opencv车辆识别报错
错误信息 ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void org.opencv.objdetect.CascadeClassifier.detectMultiScale(org.opencv.core.Mat, org.opencv.core.MatOfRect, double, int, int, org.opencv.core.Size, org.opencv.core.Size)' on a null object reference at com.example.myapplication.MainActivity.procSrc2Gray(MainActivity.java:139) at com.example.myapplication.MainActivity$ProcessClickListener.onClick(MainActivity.java:188) at android.view.View.performClick(View.java:4780) at android.view.View$PerformClick.run(View.java:19866) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) ``` 说是空指针但是找不到问题在哪里。。 求好心人帮帮我。。 ------------ 前面我有给分类器赋值 ``` public void initializeOpenCVDependencies() { try { // Copy the resource into a temp file so OpenCV can load it InputStream is = getResources().openRawResource(R.raw.cars); File cascadeDir = getDir("cars", Context.MODE_PRIVATE); File mCascadeFile = new File(cascadeDir.getAbsoluteFile(), "cars.xml"); FileOutputStream os = new FileOutputStream(mCascadeFile); byte[] buffer = new byte[4096]; int bytesRead=0; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); os.close(); // Load the cascade classifier detectface = new CascadeClassifier(mCascadeFile.getAbsolutePath()); } catch (Exception e) { Log.e("OpenCVActivity", "Error loading cascade", e); } } ```请问是不是赋值语句有问题?
Android程序在手机上运行崩溃但是在模拟器上能运行但是还有一个模拟器也是崩溃的
package darkhorse.english.app; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AutoCompleteTextView; import android.widget.CursorAdapter; import android.widget.ImageButton; import android.widget.TextView; public class LookupActivity extends Activity implements OnClickListener, TextWatcher { private final String DATABASE_PATH = android.os.Environment .getExternalStorageDirectory().getAbsolutePath() + "/dictionary"; private AutoCompleteTextView autocompletetextview; private final String DATABASE_FILENAME = "dictionary.db"; private SQLiteDatabase database; private ImageButton lookupbutton; private TextView textview; private ImageButton clearbutton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.lookup_layout); database = openDatabase(); lookupbutton = (ImageButton) findViewById(R.id.lookupbutton); textview = (TextView) findViewById(R.id.textview); clearbutton = (ImageButton) findViewById(R.id.clearbutton); autocompletetextview = (AutoCompleteTextView) findViewById(R.id.autocompletetextview); lookupbutton.setOnClickListener(this); autocompletetextview.addTextChangedListener(this); clearbutton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // TODO Auto-generated method stub autocompletetextview.setText(""); textview.setText(""); } }); } public class DictionaryAdapter extends CursorAdapter { private LayoutInflater layoutInflater; @Override public CharSequence convertToString(Cursor cursor) { return cursor == null ? "" : cursor.getString(cursor.getColumnIndex("_id")); } private void setView(View view, Cursor cursor) { TextView tvWordItem = (TextView) view; tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id"))); } @Override public void bindView(View view, Context context, Cursor cursor) { setView(view, cursor); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = layoutInflater.inflate(R.layout.word_list_item, null); setView(view, cursor); return view; } public DictionaryAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } } public void afterTextChanged(Editable s) { // 必须将English字段的别名设为_id Cursor cursor = database.rawQuery( "select english as _id from t_words where english like ?", new String[] { s.toString() + "%" }); DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this, cursor, true); autocompletetextview.setAdapter(dictionaryAdapter); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } public void onClick(View view) { String sql = "select chinese from t_words where english=?"; Cursor cursor = database.rawQuery(sql, new String[] { autocompletetextview.getText().toString() }); String result = "未找到该单词."; // 如果查找单词,显示其中文的意思 if (cursor.getCount() > 0) { // 必须使用moveToFirst方法将记录指针移动到第1条记录的位置 cursor.moveToFirst(); result = cursor.getString(cursor.getColumnIndex("chinese")); } // 显示查询结果对话框 textview.setText(result); } private SQLiteDatabase openDatabase() { try { // 获得dictionary.db文件的绝对路径 String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME; File dir = new File(DATABASE_PATH); // 如果/sdcard/dictionary目录中存在,创建这个目录 if (!dir.exists()) dir.mkdir(); // 如果在/sdcard/dictionary目录中不存在 // dictionary.db文件,则从res\raw目录中复制这个文件到 // SD卡的目录(/sdcard/dictionary) if (!(new File(databaseFilename)).exists()) { // 获得封装dictionary.db文件的InputStream对象 InputStream is = getResources().openRawResource( R.raw.dictionary); FileOutputStream fos = new FileOutputStream(databaseFilename); byte[] buffer = new byte[8192]; int count = 0; // 开始复制dictionary.db文件 while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); is.close(); } // 打开/sdcard/dictionary目录中的dictionary.db文件 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase( databaseFilename, null); return database; } catch (Exception e) { } return null; } } 求高手给看看
为什么我自制的andriod词典一输入就退出
package com.aaaa.aaaa; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.TextView; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class MainActivity extends Activity implements OnClickListener, TextWatcher { // 定义数据库的存放路径 private final String DATABASE_PATH = android.os.Environment .getExternalStorageDirectory().getAbsolutePath() + "/dictionary"; // 用户输入文本框 private AutoCompleteTextView word; // 定义数据库的名字 private final String DATABASE_FILENAME = "dictionary.db"; private SQLiteDatabase database; private Button searchWord; // 用户显示查询结果 private TextView showResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 打开数据库 database = openDatabase(); searchWord = (Button) findViewById(R.id.searchWord); word = (AutoCompleteTextView) findViewById(R.id.word); // 绑定监听器 searchWord.setOnClickListener(this); word.addTextChangedListener(this); showResult = (TextView) findViewById(R.id.result); } public class DictionaryAdapter extends CursorAdapter { private LayoutInflater layoutInflater; public DictionaryAdapter(Context context, Cursor c, boolean flags) { super(context, c, flags); layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public CharSequence convertToString(Cursor cursor) { return cursor == null ? "" : cursor.getString(cursor .getColumnIndex("_id")); } // 生成新的选项 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = layoutInflater.inflate(R.layout.word_list_item, null); setView(view, cursor); return view; } // 绑定选项到列表中 @Override public void bindView(View view, Context context, Cursor cursor) { setView(view, cursor); } // 将单词信息显示到列表中 private void setView(View view, Cursor cursor) { TextView tvWordItem = (TextView) view; tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id"))); } } // 打开数据库 private SQLiteDatabase openDatabase() { try { // 获得dictionary.db文件的绝对路径 String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME; File dir = new File(DATABASE_PATH); // 如果目录不存在,则创建这个目录 if (!dir.exists()) { dir.mkdir(); } // 如果在/sdcard/dictionary目录中不存在 // dictionary.db文件,则从res\raw目录中复制这个文件到 // SD卡的目录(/sdcard/dictionary) if (!(new File(databaseFilename)).exists()) { // 获得封装dictionary.db文件的InputStream对象 InputStream is = getResources().openRawResource( R.raw.dictionary); FileOutputStream fos = new FileOutputStream(databaseFilename); byte[] buffer = new byte[8192]; int count = 0; // 开始复制dictionary.db文件 while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } // 关闭文件流 fos.close(); is.close(); } // 打开/sdcard/dictionary目录中的dictionary.db文件 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase( databaseFilename, null); return database; } catch (Exception e) { e.printStackTrace(); } return null; } @Override public void onClick(View v) { // 查询指定的单词 String sql = "select chinese from t_words where english=?"; Cursor cursor = database.rawQuery(sql, new String[] { word.getText() .toString() }); String result = "未找到该单词."; // 如果查找单词,显示其中文的意思 if (cursor.getCount() > 0) { // 必须使用moveToFirst方法将记录指针移动到第1条记录的位置 cursor.moveToFirst(); result = cursor.getString(cursor.getColumnIndex("chinese")) .replace("&", "&"); } // 将结果显示到TextView中 showResult.setText(word.getText() + "\n" + result.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { // 必须将english字段的别名设为_id Cursor cursor = database.rawQuery( "select english as _id from t_words where english like ?", new String[] { s.toString() + "%" }); // 新建新的Adapter DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this, cursor, true); // 绑定适配器 word.setAdapter(dictionaryAdapter); } }
jsp将图片以二进制的形式存入mysql中,再读出来的时候机器快卡死了,请教各位帮我解决,
[size=small]jsp将图片以二进制的形式存入mysql中,再读出来的时候机器快卡死了,我也关闭了数据库连接,也清除了缓存,[/size] [color=darkblue] <%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.sql.*"%> <%@ page import="java.util.*"%> <%@ page import="java.text.*"%> <%@ page import="java.io.*"%> <%@page import="com.dba.DataBaseConnection"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'testimageout.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% Connection con = DataBaseConnection.getConnection(); PreparedStatement stmt = con.prepareStatement("select imgefile from controlimg WHERE id=?"); ResultSet rs = null; //建立ResultSet(结果集)对象 int id =new Integer(request.getParameter("id")); //获得所要显示图片的编号id,并转换为整型 stmt.setInt(1,id); //要执行查询的SQL语句 rs = stmt.executeQuery(); ServletOutputStream sout =null; InputStream in=null; byte b[] =null; while (rs.next()) { sout = response.getOutputStream(); //图片输出的输出流 in = rs.getBinaryStream(1); b = new byte[0x7a120]; for (int i = in.read(b); i != -1;) { sout.write(b); //将缓冲区的输入输出到页面 in.read(b); } sout.flush(); sout.close(); in.close(); } rs.close(); con.close(); out.flush(); out.close(); //输入完毕,清除缓冲 %> </body> </html>[/color][color=green]以上代码保存在了timeimgeout.jsp中了,[/color] <%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.sql.*"%> <%@page import="com.dba.DataBaseConnection"%> <html> <head> <title>动态显示数据库图片</title> </head> <body> <% Connection con = DataBaseConnection.getConnection(); PreparedStatement stmt = con .prepareStatement("select id from controlimg"); ResultSet rs = stmt.executeQuery(); rs.last(); //将指针移至最后一条记录 %> <table> <tr> <td> <IMG height=99 src="testimageout.jsp?id=<%=rs.getInt("id")%>" width=136> </td> </tr> </table> <% rs.close(); con.close(); response.flushBuffer(); out.close(); %> </body> </html> 在这个文件中输出了此图片,输出来后机器太卡了,内存几乎占完了,怎么解决,希望各位多多指教,谢谢 当关闭浏览器时出现如下异常: 严重: Servlet.service() for servlet jsp threw exception java.net.SocketException: Connection reset by peer: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(Unknown Source) at java.net.SocketOutputStream.write(Unknown Source) at org.apache.coyote.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:764) at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:129) at org.apache.coyote.http11.InternalOutputBuffer.doWrite(InternalOutputBuffer.java:570) at org.apache.coyote.Response.doWrite(Response.java:560) at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:353) at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:354) at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:381) at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:370) at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:89) at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:83) at org.apache.jsp.normal.testimageout_jsp._jspService(testimageout_jsp.java:118) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) 请教各位帮我解决,
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私有的数
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
此博客仅为我业余记录文章所用,发布到此,仅供网友阅读参考,如有侵权,请通知我,我会删掉。 补充 有不少读者留言说本文章没有用,因为天气预报直接打开手机就可以收到了,为何要多此一举发送到邮箱呢!!!那我在这里只能说:因为你没用,所以你没用!!! 这里主要介绍的是思路,不是天气预报!不是天气预报!!不是天气预报!!!天气预报只是用于举例。请各位不要再刚了!!! 下面是我会用到的两个场景: 每日下
Python 植物大战僵尸代码实现(2):植物卡片选择和种植
这篇文章要介绍的是: - 上方植物卡片栏的实现。 - 点击植物卡片,鼠标切换为植物图片。 - 鼠标移动时,判断当前在哪个方格中,并显示半透明的植物作为提示。
死磕YOLO系列,YOLOv1 的大脑、躯干和手脚
YOLO 是我非常喜欢的目标检测算法,堪称工业级的目标检测,能够达到实时的要求,它帮我解决了许多实际问题。 这就是 YOLO 的目标检测效果。它定位了图像中物体的位置,当然,也能预测物体的类别。 之前我有写博文介绍过它,但是每次重新读它的论文,我都有新的收获,为此我准备写一个系列的文章来详尽分析它。这是第一篇,从它的起始 YOLOv1 讲起。 YOLOv1 的论文地址:https://www.c
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
记一次腾讯面试:进程之间究竟有哪些通信方式?如何通信? ---- 告别死记硬背
有一次面试的时候,被问到进程之间有哪些通信方式,不过由于之前没深入思考且整理过,说的并不好。想必大家也都知道进程有哪些通信方式,可是我猜很多人都是靠着”背“来记忆的,所以今天的这篇文章,讲给大家详细着讲解他们是如何通信的,让大家尽量能够理解他们之间的区别、优缺点等,这样的话,以后面试官让你举例子,你也能够顺手拈来。 1、管道 我们来看一条 Linux 的语句 netstat -tulnp | gr...
20行Python代码爬取王者荣耀全英雄皮肤
引言 王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了。我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成。 准备工作 爬取皮肤本身并不难,难点在于分析,我们首先得得到皮肤图片的url地址,话不多说,我们马上来到王者荣耀的官网: 我们点击英雄资料,然后随意地选择一位英雄,接着F12打开调试台,找到英雄原皮肤的图片
网络(8)-HTTP、Socket、TCP、UDP的区别和联系
TCP/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据。 一、TCP与UDP的不同 1. 是否需要建立连接。 UDP在传送数据之前不需要先建立连接;TCP则提供面向连接的服务; 2. 是否需要给出确认 对方的传输层在收到UDP报文后,不需要给出任何确认,而 TCP需要给出确认报文,要提供可靠的、面向连接的传输服务。 3.虽然UDP不提供可靠交...
简明易理解的@SpringBootApplication注解源码解析(包含面试提问)
欢迎关注文章系列 ,关注我 《提升能力,涨薪可待》 《面试知识,工作可待》 《实战演练,拒绝996》 欢迎关注我博客,原创技术文章第一时间推出 也欢迎关注公 众 号【Ccww笔记】,同时推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《提升能力,涨薪可待篇》- @SpringBootApplication注解源码解析 一、@SpringBootApplication 的作用是什
防劝退!数据结构和算法难理解?可视化动画带你轻松透彻理解!
大家好,我是 Rocky0429,一个连数据结构和算法都不会的蒟蒻… 学过数据结构和算法的都知道这玩意儿不好学,没学过的经常听到这样的说法还没学就觉得难,其实难吗?真难! 难在哪呢?当年我还是个小蒟蒻,初学数据结构和算法的时候,在忍着枯燥看完定义原理,之后想实现的时候,觉得它们的过程真的是七拐八绕,及其难受。 在简单的链表、栈和队列这些我还能靠着在草稿上写写画画理解过程,但是到了数论、图...
西游记团队中如果需要裁掉一个人,会先裁掉谁?
2019年互联网寒冬,大批企业开始裁员,下图是网上流传的一张截图: 裁员不可避免,那如何才能做到不管大环境如何变化,自身不受影响呢? 我们先来看一个有意思的故事,如果西游记取经团队需要裁员一名,会裁掉谁呢,为什么? 西游记团队组成: 1.唐僧 作为团队teamleader,有很坚韧的品性和极高的原则性,不达目的不罢休,遇到任何问题,都没有退缩过,又很得上司支持和赏识(直接得到唐太宗的任命,既给
开挂的人生!那些当选院士,又是ACM/IEEE 双料Fellow的华人学者们
昨日,2019年两院院士正式官宣,一时间抢占了各大媒体头条。 朋友圈也是一片沸腾,奔走相告,赶脚比自己中了大奖还嗨皮! 谁叫咱家导师就是这么厉害呢!!! 而就在最近,新一年度的IEEE/ACM Fellow也将正式公布。 作为学术届的顶级荣誉,不自然地就会将院士与Fellow作比较,到底哪个含金量更高呢? 学术君认为,同样是专业机构对学者的认可,考量标准不一,自然不能一概而论。 但...
聊聊C语言和指针的本质
坐着绿皮车上海到杭州,24块钱,很宽敞,在火车上非正式地聊几句。 很多编程语言都以 “没有指针” 作为自己的优势来宣传,然而,对于C语言,指针却是与生俱来的。 那么,什么是指针,为什么大家都想避开指针。 很简单, 指针就是地址,当一个地址作为一个变量存在时,它就被叫做指针,该变量的类型,自然就是指针类型。 指针的作用就是,给出一个指针,取出该指针指向地址处的值。为了理解本质,我们从计算机模型说起...
Python语言高频重点汇总
Python语言高频重点汇总 GitHub面试宝典仓库——点这里跳转 文章目录Python语言高频重点汇总**GitHub面试宝典仓库——点这里跳转**1. 函数-传参2. 元类3. @staticmethod和@classmethod两个装饰器4. 类属性和实例属性5. Python的自省6. 列表、集合、字典推导式7. Python中单下划线和双下划线8. 格式化字符串中的%和format9.
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
代码详解:如何用Python快速制作美观、炫酷且有深度的图表
全文共12231字,预计学习时长35分钟生活阶梯(幸福指数)与人均GDP(金钱)正相关的正则图本文将探讨三种用Python可视化数据的不同方法。以可视化《2019年世界幸福报告》的数据为例,本文用Gapminder和Wikipedia的信息丰富了《世界幸福报告》数据,以探索新的数据关系和可视化方法。《世界幸福报告》试图回答世界范围内影响幸福的因素。报告根据对“坎特里尔阶梯问题”的回答来确定幸...
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外
(经验分享)作为一名普通本科计算机专业学生,我大学四年到底走了多少弯路
今年正式步入了大四,离毕业也只剩半年多的时间,回想一下大学四年,感觉自己走了不少弯路,今天就来分享一下自己大学的学习经历,也希望其他人能不要走我走错的路。 (一)初进校园 刚进入大学的时候自己完全就相信了高中老师的话:“进入大学你们就轻松了”。因此在大一的时候自己学习的激情早就被抛地一干二净,每天不是在寝室里玩游戏就是出门游玩,不过好在自己大学时买的第一台笔记本性能并不是很好,也没让我彻底沉...
如何写一篇技术博客,谈谈我的看法
前言 只有光头才能变强。 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y 我一直推崇学技术可以写技术博客去沉淀自己的知识,因为知识点实在是太多太多了,通过自己的博客可以帮助自己快速回顾自己学过的东西。 我最开始的时候也是只记笔记,认为自己能看得懂就好。但如果想验证自己是不是懂了,可以写成技术博客。在写技术博客的...
字节跳动面试官这样问消息队列:分布式事务、重复消费、顺序消费,我整理了一下
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
面试还搞不懂redis,快看看这40道面试题(含答案和思维导图)
Redis 面试题 1、什么是 Redis?. 2、Redis 的数据类型? 3、使用 Redis 有哪些好处? 4、Redis 相比 Memcached 有哪些优势? 5、Memcache 与 Redis 的区别都有哪些? 6、Redis 是单进程单线程的? 7、一个字符串类型的值能存储最大容量是多少? 8、Redis 的持久化机制是什么?各自的优缺点? 9、Redis 常见性...
大学四年自学走来,这些珍藏的「实用工具/学习网站」我全贡献出来了
知乎高赞:文中列举了互联网一线大厂程序员都在用的工具集合,涉及面非常广,小白和老手都可以进来看看,或许有新收获。
互联网公司的裁员,能玩出多少种花样?
裁员,也是一门学问,可谓博大精深!以下,是互联网公司的裁员的多种方法:-正文开始-135岁+不予续签的理由:千禧一代网感更强。95后不予通过试用期的理由:已婚已育员工更有责任心。2通知接下来要过苦日子,让一部分不肯同甘共苦的员工自己走人,以“兄弟”和“非兄弟”来区别员工。3强制996。员工如果平衡不了工作和家庭,可在离婚或离职里二选一。4不布置任何工作,但下班前必须提交千字工作日报。5不给活干+...
【设计模式】单例模式的八种写法分析
网上泛滥流传单例模式的写法种类,有说7种的,也有说6种的,当然也不排除说5种的,他们说的有错吗?其实没有对与错,刨根问底,写法终究是写法,其本质精髓大体一致!因此完全没必要去追究写法的多少,有这个时间还不如跟着宜春去网吧偷耳机、去田里抓青蛙得了,一天天的....
《面试宝典》:检验是否为合格的初中级程序员的面试知识点,你都知道了吗?查漏补缺
欢迎关注文章系列,一起学习 《提升能力,涨薪可待篇》 《面试知识,工作可待篇》 《实战演练,拒绝996篇》 也欢迎关注公 众 号【Ccww笔记】,原创技术文章第一时间推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《面试知识,工作可待篇》-Java笔试面试基础知识大全 前言 是不是感觉找工作面试是那么难呢? 在找工作面试应在学习的基础进行总结面试知识点,工作也指日可待,欢...
关于研发效能提升的思考
研发效能提升是最近比较热门的一个话题,本人根据这几年的工作心得,做了一些思考总结,由于个人深度有限,暂且抛转引入。 三要素 任何生产力的提升都离不开这三个因素:人、流程和工具,少了其中任何一个因素都无法实现。 人,即思想,也就是古人说的“道”,道不同不相为谋,是制高点,也是高层建筑的基石。 流程,即方法,也是古人说的“法”。研发效能的提升,也就是要提高投入产出比,既要增加产出,也要减...
微博推荐算法简述
在介绍微博推荐算法之前,我们先聊一聊推荐系统和推荐算法。有这样一些问题:推荐系统适用哪些场景?用来解决什么问题、具有怎样的价值?效果如何衡量? 推荐系统诞生很早,但真正被大家所重视,缘起于以”facebook”为代表的社会化网络的兴起和以“淘宝“为代表的电商的繁荣,”选择“的时代已经来临,信息和物品的极大丰富,让用户如浩瀚宇宙中的小点,无所适从。推荐系统迎来爆发的机会,变得离用户更近: 快...
相关热词 c#如何定义数组列表 c#倒序读取txt文件 java代码生成c# c# tcp发送数据 c#解决时间格式带星期 c#类似hashmap c#设置istbox的值 c#获取多线程返回值 c# 包含数字 枚举 c# timespan
立即提问