简体   繁体   English

具有字符串和指定长度的Java类

[英]Java Class with string and a specified length

I'm creating a java program that creates a file and fills it with data in string form with each field in the record limited to a specific length. 我正在创建一个Java程序,该程序创建一个文件,并用字符串形式的数据填充该文件,并将记录中的每个字段限制为特定长度。

What I think I need to do is to create a class that has a string for the data field and a length specifying the length of the string. 我想我需要做的是创建一个类,该类具有一个用于数据字段的字符串以及一个用于指定字符串长度的长度。 And then somehow restrict it so that the string never exceeds this length, either by bailing, padding with whitespace (if the data input is less that the length) or truncating the end so the data fits. 然后以某种方式限制它,以使字符串永远不会超过此长度,方法是通过打包,用空格填充(如果数据输入小于该长度)或截断末尾以使数据适合,则该字符串永远不会超过此长度。

My first question is if there is already a basic class that will do this, or should I just roll my own. 我的第一个问题是,是否已经有一个基本的类可以做到这一点,或者我应该自己动手做。

My second question is if I do roll my own how do I make sure when the class is constructed that the initial value of the internal String is less than the length specified, Ive read elsewhere that a constructor should return a value, but is it valid for a constructor to raise an exception? 我的第二个问题是,如果我自己动手,如何确保在构造类时,内部String的初始值小于指定的长度,我在其他地方读过,构造函数应返回值,但它是否有效?为构造函数引发异常?

Thanks for any help. 谢谢你的帮助。

Here's my take - it meets all the requirements in your question. 这是我的看法-它满足您问题中的所有要求。 You'll note that I've chosen to reject illegal assignments with an IllegalArgumentException . 您会注意到,我选择了使用IllegalArgumentException拒绝非法分配。

package com.pragmaticsoftwaredevelopment.stackoverflow;

public class FixedLengthString {
   private String string=null;
   private int length=-1;
   public FixedLengthString(int length) { 
      this.length = length; 
   }
   public void setValue (String str) {
      if (str.length() > length)
         throw new IllegalArgumentException("ERROR: Assigned string length (" + str.length() + ") exceeded given limit (" + length + ")");
      else
         this.string = str;
   }
   public String toString() {
      return String.format("%1$-" + length + "s", string);

   }
   public String getString() { 
      return toString();
   }
}

使用printf格式

System.out.printf("\n%-5d%-20s",10,"Hello");

You can use StringUtils, which is part of Commons Lang and use the following method: 您可以使用StringUtils(它是Commons Lang的一部分),并使用以下方法:

String rightPad(java.lang.String str, int size, char padChar) 

like this: 像这样:

String myPaddedString = StringUtils.rightPad("Sample string", 20, "*") 

You can then write that to a file - take a look at Commons IO FileUtils for a neat way to write a string easily... 然后可以将其写入文件-查看Commons IO FileUtils,这是一种轻松编写字符串的巧妙方法...

On your second point.. a constructor can't return a value, otherwise it would be a standard method, but it is free to raise an exception based on the parameters passed into it - IllegalArgumentException is the most appropriate in this case. 关于第二点..构造函数无法返回值,否则它将是标准方法,但是可以根据传递给它的参数随意引发异常-在这种情况下,IllegalArgumentException最合适。

You could do something like this: 您可以执行以下操作:

public class Field {
    // other members not shown
    int length;
    String value;

    public Field(int length, String initialValue) {
        // omitted error check for length > 0
        this.length = length;
        setValue(initialValue);
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        if (value != this.value) {
            if (value == null)
                value = "";
            if value.length() > length)
                value = value.substring(0, length);
            else
                value = String.format("%1$-" + length + "s", value);
            this.value = value;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM