标签: inputstream

缓冲后台InputStream实现

我编写了包装其他流的后台InputStream(和OutputStream)实现,并在后台线程上预读,主要允许解压缩/压缩在解压缩流处理的不同线程中发生.

这是一个相当标准的生产者/消费者模型.

这似乎是一种简单的方法,可以通过简单的读取,处理和写入数据的流程来充分利用多核CPU,从而更有效地利用CPU和磁盘资源.也许"高效"并不是最好的词,但它提供了更高的利用率,对我来说更感兴趣,减少了运行时间,而不是直接从a读取ZipInputStream并直接写入ZipOutputStream.

我很高兴发布代码,但我的问题是我是否正在重新发明现有(和更多运行)库中现有的东西?

编辑 - 发布代码......

我的代码BackgroundInputStream是在下面(BackgroundOutputStream非常相似),但有一些方面我想改进.

  1. 看起来我工作得太过艰难,无法前后传递缓冲区.
  2. 如果调用代码抛弃了对引用的引用BackgroundInputStream,那么backgroundReaderThread它将永远存在.
  3. 信号eof需要改进.
  4. 应将异常传播到前台线程.
  5. 我想允许使用提供的线程Executor.
  6. close()方法应该通知后台线程,并且不应该关闭包装的流,因为包装的流应该由从其读取的后台线程拥有.
  7. 在收盘后做一些愚蠢的事情应该适当地照顾.

package nz.co.datacute.io;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.concurrent.LinkedBlockingQueue;

public class BackgroundInputStream extends InputStream {
    private static final int DEFAULT_QUEUE_SIZE = 1;
    private static final int DEFAULT_BUFFER_SIZE = 64*1024;
    private final int queueSize;
    private final int bufferSize;
    private volatile boolean eof …
Run Code Online (Sandbox Code Playgroud)

java compression multithreading inputstream producer-consumer

8
推荐指数
1
解决办法
2535
查看次数

Java检测封闭流

我有一个由OutputStream和InputStream组成的通用套接字实现.

在我做了一些工作之后,我正在关闭OutputStream.

完成后,我的InputStream的read()方法返回-1无限的时间,而不是像我预期的那样抛出异常.

我现在不确定最安全的路线,所以我有一些问题:

  • 我可以安全地假设-1仅在流关闭时返回吗?
  • 是否无法重新创建强制断开连接时发生的IO异常?
  • 我应该发送一个数据包来告诉我的InputStream它应该关闭而不是前两个方法吗?

谢谢!

java sockets inputstream outputstream

8
推荐指数
1
解决办法
7044
查看次数

阅读Android Spring Interceptor中的响应主体

我正在使用一个简单的Spring Interceptor类来记录我的Android应用程序中RestTemplate对象的所有REST请求/响应.到目前为止一切正常.

public class LoggerInterceptor implements ClientHttpRequestInterceptor {

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
  ClientHttpRequestExecution execution) throws IOException {

Log.d(TAG, "Request body: " + new String(body));
// ...more log statements...

ClientHttpResponse response = execution.execute(request, body);

Log.d(TAG, "Response Headers: " + response.getHeaders());

return response;
}
Run Code Online (Sandbox Code Playgroud)

在初始化时我打电话:

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
LoggerInterceptor loggerInterceptor = new LoggerInterceptor();
interceptors.add(loggerInterceptor);
restTemplate.setInterceptors(interceptors);
Run Code Online (Sandbox Code Playgroud)

但是我无法登录response.getBody()上面的方法,因为InputStream被消耗一次并在以后再次使用时抛出IllegalStateException.有没有解决方法,以便我也可以记录响应正文?

java spring android inputstream interceptor

8
推荐指数
2
解决办法
4399
查看次数

如何知道FTP欢迎消息的结束

我的问题是我正在创建一个FTP客户端,到目前为止它的工作完美无缺,除了一个小细节之外,一直困扰着我.我需要知道FTP欢迎消息跨越多少行......这是不可接受的!

    private Socket connection;
    private PrintWriter outStream;
    private Scanner inStream;

public void InitiateConnection() throws IOException 
{
    log.Info(this, "Initiating connection to host: " + host + ":" + port);
    connection = new Socket(host, port);
    log.Info(this, "Connection initiated.");
    outStream = new PrintWriter(connection.getOutputStream(), true);
    inStream = new Scanner(connection.getInputStream());
    Listen();
    Listen();    
    Listen();
}

public String Listen() throws IOException
{
    if(connection == null)
        throw new IOException("Connection not initiated yet");
    String response = inStream.nextLine();
    log.Info(this, "Response: " + response);
    return response;
}
Run Code Online (Sandbox Code Playgroud)

这是简单的设置,我遗漏了所有其他代码,因为它与我的问题没有任何关系.

我尝试了多种尝试来实现这一目标.解决方案1失败:

String response …
Run Code Online (Sandbox Code Playgroud)

java sockets ftp inputstream

8
推荐指数
1
解决办法
3402
查看次数

从公共方法返回InputStream

我有一个课程,一方面,InputStream从公共方法返回一个感觉是正确的,例如

public class MyClass {

    private File _file;

    ...

    public InputStream getInputStream() {
        return new FileInputStream( _file );
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我对这样做也非常谨慎,因为它让调用者有责任关闭这个流.我有什么方法可以避免这个问题?

java io inputstream

8
推荐指数
1
解决办法
9095
查看次数

保持Java蓝牙连接活跃

我正在使用Bluecove API为我的计算机构建一个简单的Java蓝牙服务器.我正在构建一个Android客户端应用程序,但问题似乎源于服务器端应用程序.

我确定有人已经在某处发布了任何答案,过去几天我已经严格尝试了不同的解决方案并查看了所有可能的论坛,但我似乎无法保持套接字线程上的连接.

我可以在从android到计算机建立连接之后交换消息,反之亦然,从计算机到android,但是在交换字节后,Bluecove堆栈关闭并关闭套接字连接,即使我没有明确告诉它connection.close()时.

我试图使用一段时间(某些陈述是真的)循环来保持连接活动,它不再在收到第一条消息后关闭套接字但它无法接收我从智能手机发送到我的计算机的任何后续消息无论是.虽然它基本上是活着的,但当我尝试从智能手机发送它们时,它无法接收任何新消息.不知道为什么.

对不起,这是我第一次发帖,我不确定为什么代码的第一部分无法在页面上正确显示.

代码连接:

public BluetoothServer()
{
    try 
    {
        service = (StreamConnectionNotifier) 
             Connector.open("btspp://localhost:" + new UUID(0x1101).toString() + 
                                ";name=SampleServer");

            System.out.println("open connection");



            while(runState == true){

                connection = (StreamConnection) service.acceptAndOpen();

//send a greeting across to android
                    outputStream = connection.openOutputStream();
                    String greeting = "JSR-82 RFCOMM server says hello";
                    outputStream.write(greeting.getBytes());

//run thread that listens for incoming bytes through socket connection
                Thread t = new Thread(new ConnectedThread(connection));
                t.start();

            }

    } catch(IOException e) {}
}
Run Code Online (Sandbox Code Playgroud)

用于收听数据的线程代码

public void run()
{
    try
    {    
            //open input …
Run Code Online (Sandbox Code Playgroud)

java bluetooth inputstream jsr82 bluecove

8
推荐指数
1
解决办法
1536
查看次数

HttpUrlConnection.getInputStream在Android中返回空流

我使用HttpUrlConnection向服务器发出GET请求.连接后:

  1. 我收到回复码:200
  2. 我收到回复消息:好的
  3. 我得到输入流,没有抛出异常但是:

    • 在一个独立的程序中,我按预期得到了响应的主体:

    {"name":"我的名字","生日":"01/01/1970","id":"100002215110084"}

    • 在android活动中,流是空的(available()== 0),因此我无法获取任何文本.

是否有任何提示或追踪?谢谢.

编辑:这是代码

请注意:我使用import java.net.HttpURLConnection;这是标准的http Java库.我不想使用任何其他外部库.事实上,我确实在使用来自apache的库httpclient的android中遇到了问题(他们的一些匿名.class不能被apk编译器使用).

嗯,代码:

URLConnection theConnection;
theConnection = new URL("www.example.com?query=value").openConnection(); 

theConnection.setRequestProperty("Accept-Charset", "UTF-8");

HttpURLConnection httpConn = (HttpURLConnection) theConnection;


int responseCode = httpConn.getResponseCode();
String responseMessage = httpConn.getResponseMessage();

InputStream is = null;
if (responseCode >= 400) {
    is = httpConn.getErrorStream();
} else {
    is = httpConn.getInputStream();
}


String resp = responseCode + "\n" + responseMessage + "\n>" + Util.streamToString(is) + "<\n";

return resp;
Run Code Online (Sandbox Code Playgroud)

我知道了:

200
OK
回复的正文

但是只有

200好的 …

android inputstream httpurlconnection

8
推荐指数
1
解决办法
3万
查看次数

如何模拟javax.servlet.ServletInputStream

我正在创建一些单元测试并尝试模拟一些调用.这是我在工作代码中的内容:

String soapRequest = (SimUtil.readInputStream(request.getInputStream())).toString();
if (soapRequest.equals("My String")) { ... }
Run Code Online (Sandbox Code Playgroud)

和SimUtil.readInputSteam看起来像这样:

StringBuffer sb = new StringBuffer();
BufferedReader reader = null;
try  {
    reader = new BufferedReader(new InputStreamReader(inputStream));
    final int buffSize = 1024;
    char[] buf = new char[buffSize];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        sb.append(readData);
        buf = new char[buffSize];
    }
} catch (IOException e) {
    LOG.error(e.getMessage(), e);
} finally {
    try {
        if (reader != null) {
            reader.close();
        } …
Run Code Online (Sandbox Code Playgroud)

java unit-testing servlets inputstream mockito

8
推荐指数
1
解决办法
1万
查看次数

Jersey POST请求并关闭InputStream

当我在Jersey中有一个方法来监听POST请求时,当我在我想要获取数据的方法中有一个InputStream作为参数时,我是否需要关闭此InputStream或者Jersey会处理这个?

我还没有找到任何相关信息.我曾经用JAX-RS 2.0读过RESTful Java,我不记得是否提到过.现在浏览一下,我找到了几个代码示例,并且没有关闭流.我认为没有必要,但想问.

inputstream jax-rs jersey

8
推荐指数
1
解决办法
1402
查看次数

未调用JAXB ValidationEventHandler的handleEvent方法

我正在尝试捕获ValidationEventXML规则中不允许的字符。(例如,“&”)此外,我设置ValidationEventHandler为检查非编组错误。我尝试使用进行解组InputStream,但事件处理程序未捕获该错误。handleEvent方法根本不执行。另一方面,使用StringReader将正常工作。

我已经阅读了描述该unmarshal方法的Javadoc 。但是,我没有看到它无法捕获ValidationEvent。

从指定的InputStream解组XML数据,并返回结果内容树。使用这种形式的解组API时,验证事件位置信息可能不完整。

在最后一次尝试中,我确实尝试过在线搜索,但找不到任何东西。
任何帮助将不胜感激:D

额外的问题:

很抱歉添加一个问题。(POJO类有所更改...)我用与@XmlPathXML元素名称不同的Annotation定义了POJO类字段,但似乎不起作用。我应该将其用作XmlElement吗?


POJO类:

import org.eclipse.persistence.oxm.annotations.XmlPath;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@XmlRootElement
class Article {
    private String title;
    private String category;
    private List<ArticleImage> imageList;

    public String getTitle() {
        return title;
    }

    @XmlElement
    public void setTitle(String title) {
        this.title = title;
    }

    public String getCategory() {
        return category;
    }

    @XmlElement
    public void setCategory(String …
Run Code Online (Sandbox Code Playgroud)

java inputstream jaxb unmarshalling java-8

8
推荐指数
1
解决办法
350
查看次数