相关疑难解决方法(0)

如何为字节数组赋值

byte abc[]="204.29.207.217";
Run Code Online (Sandbox Code Playgroud)

这是一个错误.请告诉我正确的方法.

java bytearray

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

如何将ZipInputStream转换为InputStream?

我有代码,ZipInputSream转换为byte [],但我不知道如何将其转换为inputstream.

private void convertStream(String encoding, ZipInputStream in) throws IOException,
        UnsupportedEncodingException
{
    final int BUFFER = 1;
    @SuppressWarnings("unused")
    int count = 0;
    byte data[] = new byte[BUFFER];
    while ((count = in.read(data, 0, BUFFER)) != -1) 
    {
       // How can I convert data to InputStream  here ?                    
    }
}
Run Code Online (Sandbox Code Playgroud)

java inputstream zipinputstream

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

套接字 InputStream 和 UTF-8

我正在尝试与 Java 聊天。一切正常,除了特殊字符不起作用。我认为这是一个编码问题,因为我Outputstream在 UTF-8 中对字符串进行编码,如下所示:

  protected void send(String msg) {
    
        try {
          msg+="\r\n";            
          OutputStream outStream = socket.getOutputStream();              
          outStream.write(msg.getBytes("UTF-8"));
          System.out.println(msg.getBytes("UTF-8"));
          outStream.flush();
        }
        catch(IOException ex) {
          ex.printStackTrace();
        }
      }
Run Code Online (Sandbox Code Playgroud)

但在我的receive方法中,我没有找到一种方法来做到这一点:

public String receive() throws IOException {
   
    String line = "";
    InputStream inStream = socket.getInputStream();    
                
    int read = inStream.read();
    while (read!=10 && read > -1) {
      line+=String.valueOf((char)read);
      read = inStream.read();
    }
    if (read==-1) return null;
    line+=String.valueOf((char)read);       
    return line; 
    
  }
Run Code Online (Sandbox Code Playgroud)

那么有没有一种快速的方法来指定缓冲区读取的字节是用 UTF-8 编码的?

编辑:好的,我试过BufferedReader这样的:

 public String receive() throws …
Run Code Online (Sandbox Code Playgroud)

java sockets encoding utf-8

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

Base64编码图像并在JS上渲染它

我正在尝试使用Java对64位图像进行编码,如下所示

public static String getImageStream(String latitude, String longitude) {
    byte[] result = null;
    try {
        URL url = new URL(....);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.close();
        InputStream iSteamReader = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(iSteamReader));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        reader.close();
        result = response.toString().getBytes("utf-8");
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        result = new byte[0];
    }
    return Base64.getEncoder().encodeToString(result);
}
Run Code Online (Sandbox Code Playgroud)

这给了我一张表格的图片 …

javascript java

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

用html中的base64字符串显示图像?

这是我的java代码,它从image构造base64字符串.然后放置base64 String html,以查看构造的图像,但不以某种方式构建图像

public void getBase64String() throws FileNotFoundException {
    FileInputStream itStrm = new FileInputStream(
    "E:\\image\\56255254-flower.jpg");//image is lying at http://danny.oz.au/travel/mongolia/p/56255254-flower.jpg
    String str = itStrm.toString();
    byte[] b3 = str.getBytes();
    String base64String = new sun.misc.BASE64Encoder().encode(b3);
    //output of base64String is amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA==
  }
Run Code Online (Sandbox Code Playgroud)

现在在html页面中我将base64String的输出放在img标签中以查看图像.但是没有显示图像(而是显示交叉图像图标).我没有从base64字符串下面显示图像?

      <HTML>
      <BODY>
           <img    src="data:image/jpeg;base64,amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA=="/>

     </BODY>
     </HTML>
Run Code Online (Sandbox Code Playgroud)

编辑: -谢谢Folks,我使用byte [] bytes = IOUtils.toByteArray(is);. 它对我有用!!

html java base64 image

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

如何将Part转换为Blob,以便将其存储在MySQL中?

如何将Part转换为Blob,以便将其存储在MySQL中?这是一张图片.谢谢

我的表格

<h:form id="form" enctype="multipart/form-data">
        <h:messages/>
        <h:panelGrid columns="2">
            <h:outputText value="File:"/>
            <h:inputFile id="file" value="#{uploadPage.uploadedFile}"/>
        </h:panelGrid>
        <br/><br/>
        <h:commandButton value="Upload File" action="#{uploadPage.uploadFile}"/>
</h:form>
Run Code Online (Sandbox Code Playgroud)

我的豆子

@Named
@ViewScoped
public class UploadPage {       
    private Part uploadedFile; 

    public void uploadFile(){
    }
}
Run Code Online (Sandbox Code Playgroud)

jsf blob file-upload

2
推荐指数
1
解决办法
5677
查看次数

Java:以引用打印形式对字符串进行编码

我正在寻找一种quoted-printable在 Java 中对字符串进行编码的方法,就像 php 的本机quoted_printable_encode()函数一样。

我尝试过使用 JavaMails 的 MimeUtility 库。但我无法让该encode(java.io.OutputStream os, java.lang.String encoding)方法工作,因为它采用 OutputStream 作为输入而不是字符串(我使用该函数getBytes()来转换字符串)并输出一些我无法返回到字符串的内容(我是一个 Java 菜鸟:)

谁能告诉我如何编写一个包装器,将字符串转换为 OutputStream 并在编码后将结果输出为字符串?

java mime jakarta-mail quoted-printable

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

如何从Hadoop序列文件中提取数据?

Hadoop序列文件真的很奇怪.我将图像打包成序列文件,无法恢复图像.我做了一些简单的测试.我发现在使用序列文件之前和之后字节的大小甚至不相同.

Configuration confHadoop = new Configuration();
        FileSystem fs = FileSystem.get(confHadoop);

        String fileName = args[0];
        Path file = new Path(fs.getUri().toString() + "/" + fileName);
        Path seqFile = new Path("/temp.seq");
        SequenceFile.Writer writer = null;
        FSDataInputStream in = null;
        try{
            writer = SequenceFile.createWriter(confHadoop,Writer.file(seqFile), Writer.keyClass(Text.class),
                    Writer.valueClass(BytesWritable.class));

            in = fs.open(file);
            byte buffer[] = IOUtils.toByteArray(in);


            System.out.println("original size ---->  " + String.valueOf(buffer.length));
            writer.append(new Text(fileName), new BytesWritable(buffer));
            System.out.println(calculateMd5(buffer));
            writer.close();

        }finally{
            IOUtils.closeQuietly(in);
        }

        SequenceFile.Reader reader = new SequenceFile.Reader(confHadoop, Reader.file(seqFile));

        Text key = new Text();
        BytesWritable val = new BytesWritable(); …
Run Code Online (Sandbox Code Playgroud)

compression hadoop bytearray sequencefile

2
推荐指数
1
解决办法
2259
查看次数

无法解析方法 readAllBytes()

我想做什么

我正在尝试构建一个 java.net 应用程序,其中客户端和服务器必须通过序列化集合类型作为byte[].

问题

由于未知原因,我的 DataInputStream 无法解析该方法readAllBytes()

一个朋友把它扔进了他的 IDE,它没有抱怨。我不确定这怎么可能是一个版本问题,但我检查过并且我没有错误配置我的项目。我正在使用 Java 8。

  public void startClient() {
        try {
            Socket client = new Socket("localhost", 7000);
            DataOutputStream out = new DataOutputStream(client.getOutputStream());
            out.writeUTF("Hi i'm " + client.getLocalSocketAddress());
            DataInputStream input = new DataInputStream(client.getInputStream());
            byte[] sent = input.readAllBytes(); //"can't resolve method 'readAllBytes()'
            getDataFromClient(input.readAllByes());
//"can't resolve method 'readAllBytes()'
            client.close();


        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我实际上确定应该支持此方法,但我无法弄清楚为什么不支持,因为它被列为从 Input Stream (docs.oracle.com) 继承的方法

包含该方法的项目也是一个 Gradle …

java client-server gradle

2
推荐指数
1
解决办法
2602
查看次数

从Java中获取没有已知大小的InputStream的字节数组?

我通过套接字发送一个字节数组,我通过DataInputStream接收它.我不知道字节数组的大小,也没办法检查.我试过这样做:

byte[] content = new byte[ARRAY_SIZE]; 
int something; 

while((something = inFromStream.read()) > 0)  
    output.write(something); 
Run Code Online (Sandbox Code Playgroud)

但是,这仍然意味着我需要知道字节数组的大小.我不想只填写一个巨大的数字(因为从流中接收的字节数组可能是100或甚至5000000000).我该如何处理(最好使用标准的Java API /库)?

java bytearray inputstream stream

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

字节数组在java文件中没有覆盖,

下面的代码从HTTP请求获取一个字节数组并将其保存在bytes []中,最终数据将保存在message []中.

我通过将其转换为String []来检查它是否包含标题,如果我这样做,我会从标题中读取一些信息,然后通过将标题之后的字节保存到message []来将其剪掉.

然后我尝试使用FileOutputStream将message []输出到文件,它稍微有效,但只保存10KB的信息,while循环的一次迭代,(似乎是覆盖),如果我将FileOutputStream(file,true)设置为附加信息,它工作...一次,然后文件刚刚添加到下次我运行它,这不是我想要的.如何在每次迭代中使用多个字节块写入同一文件,但如果再次运行程序,仍会完整覆盖文件?

byte bytes[] = new byte[(10*1024)];
            while (dis.read(bytes) > 0)
            {
                //Set all the bytes to the message
                byte message[] = bytes;
                String string = new String(bytes, "UTF-8");

                //Does bytes contain header?
                if (string.contains("\r\n\r\n")){
                    String theByteString[] = string.split("\r\n\r\n");
                    String theHeader = theByteString[0];
                    String[] lmTemp = theHeader.split("Last-Modified: ");
                    String[] lm = lmTemp[1].split("\r\n");
                    String lastModified = lm[0];
                    //Cut off the header and save the rest of the data after it
                    message = theByteString[1].getBytes("UTF-8");

                    //cache
                    hm.put(url, …
Run Code Online (Sandbox Code Playgroud)

java arrays fileoutputstream

0
推荐指数
1
解决办法
271
查看次数