【问题标题】:Missing characters in string java字符串java中缺少字符
【发布时间】:2015-03-15 04:13:54
【问题描述】:

我正在尝试使用 http 框架实现 java 服务器,我有几个 URI:/login.jsp 和 /logout.jsp,它们可以在 http 格式的 Request URI 中找到。

当我向服务器发送注销请求时,我会使用如下标头发送它:

Cookie: user_auth="SomeCookie".

代码如下:

public HttpMessage nextMessage() {
    if (!isAlive()) {
        try {
            throw new IOException("Tokenizer is Closed");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Return String
    HttpMessage newMessage = null;
    String output = null;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        int c;

        while ((c = this.fInputStream.read()) != -1) {
            if (c == this.fDelimiter)
                break;
            else
                stringBuilder.append((char) c);
        }
        // Create an HttpMessage from the information received
        output = stringBuilder.toString();

    } catch (IOException e) {
        this.fClosed = true;
        try {
            throw new IOException("Connection is Dead");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    newMessage = parseHttp(output);
    return newMessage;
}

parseHttp 方法将类型和标头分开。

但问题是在向服务器发送 login 操作后,如果我尝试发送 logout 操作,则存储在字符串生成器中的解析信息缺少字符(更多特别是 RequestType、RequestURI 和 HttpVersion )丢失,只能找到标头。

此外,如果我尝试打印从 inputStream 收到的每个字符,我会看到所有应该在框架中的字符。

【问题讨论】:

    标签: java tcp server tokenize stringbuilder


    【解决方案1】:

    您确定要使用break; 行而不是continue; break 会导致while 循环退出,而使用continue 会跳过else 并运行while 循环的下一次迭代。

    【讨论】:

    • 谢谢!虽然 continue 在这里不起作用,但我暗示了可能是什么问题。我的代码的问题是空字符留在 inputStreamReader 中,下次我尝试从流中读取时,我收到的第一个字符是空字符,尽管奇怪的是我仍然可以读取其他字符,直到下一个分隔符..
    【解决方案2】:

    以下代码通过删除重复项打印给定字符串中的所有缺失字符。

    import java.util.*;
    public class MissChars
    {
     public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String str=sc.nextLine();
        StringBuffer sb=new StringBuffer();
        char c[]=str.toCharArray();
        LinkedHashSet<Character> set=new LinkedHashSet<Character>();
        for(int i=0;i<c.length;i++)
          set.add(c[i]);
        for(char cc:set)
          sb.append(cc);
        String sss=new String(sb);
        char arr[]=sss.toCharArray();
        for(char i='a';i<='z';i++)
        {
            for(int j=0;j<arr.length;j++)
            {
                if(i!=arr[j])
                    count++;
                if(count==arr.length)
                  System.out.print(i);
            }
            count=0;
        }
     }
    }
    

    【讨论】:

    • 这是一个通过删除重复项来打印给定字符串中所有缺失字符的代码。希望此代码对您有所帮助..
    • 您最好在答案中写下您的评论!查看我的编辑并删除您的评论。
    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2018-10-02
    • 1970-01-01
    相关资源
    最近更新 更多