如何在多行且没有标题的“ groovy”中编写一个.csv文件(预期避免附加)?

时间:2019-05-25 12:06:41

标签: groovy

class csv {
    static void main(String[] args) {
        def itemName
        def itemPrice
        def itemQty
        def list3 = []
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
        File file = new File("/Users/m_328522/Desktop/" + "invoicedetails.csv")
        file.createNewFile()
        println("Enter the number of items:")
        def noOfItems = br.readLine().toInteger()
        for (int i = 0; i < noOfItems; i++) {
            println("Enter item " + (i + 1) + " details:")
            itemName = br.readLine()
            list3 << itemName
            itemPrice = br.readLine().toDouble()
            list3 << itemPrice
            itemQty = br.readLine().toInteger()
            list3 << itemQty
            //println(list3)
            def asString = list3.join(",")
            file.append(asString +"\n")
            //println(asString)
            list3.remove(2)
            list3.remove(1)
            list3.remove(0)
            //println(list3)
        }
        println("invoicedetails.csv")
        println(file.text)
    }
}

1 个答案:

答案 0 :(得分:0)

以下代码:

def home = System.properties['user.home']
def file = new File("${home}/Desktop/invoicedetails.csv")

if (!file.isFile() && !file.createNewFile()) { 
  println "Failed to create file: $file"
  return
}

int lineCount = prompt("Enter the number of items") as Integer

file.withPrintWriter { pw -> 
  lineCount.times { i ->  
    readRecord(i, pw)
  }
}

def readRecord(i, pw) {
  println "- enter details for item ${i+1} -"

  def line = []
  line << prompt("name")
  line << prompt("price").toDouble()
  line << prompt("quantity").toInteger()

  pw.println(line.join(','))
}

def prompt(question) {
  System.console().readLine("${question} > ") 
}

应该解决您的问题。下面是一个示例运行:

~>  groovy solution.groovy

Enter the number of items > 2
- enter details for item 1 -
name > Jet Pack
price > 9999.99
quantity > 2
- enter details for item 2 -
name > Plane Desnaking Kit
price > 24999.99
quantity > 1

~> cat ~/Desktop/invoicedetails.csv
Jet Pack,9999.99,2
Plane Desnaking Kit,24999.99,1

~>

应该注意,如果除了您自己之外的任何人都将要运行此程序,则可能应包括错误处理,例如当人们要求输入数量等时进入one的人等。这可以通过以下方法实现(其余代码保持不变):

def readRecord(i, pw) {
  println "- enter details for item ${i+1} -"

  def line = []
  line << prompt("name")
  line << prompt("price", Double)
  line << prompt("quantity", Integer)

  pw.println(line.join(','))
}

def prompt(question, clazz=String) {
  boolean valid = false
  def answer 
  while (!valid) { 
    try { 
      answer = System.console().readLine("${question} > ").asType(clazz)
      valid = true
    } catch (Exception e) {
      println "-> invalid answer format for type ${clazz.simpleName}"
      println "-> please try again!"
    }
  }

  answer
}

运行示例:

~> groovy solution.groovy

Enter the number of items > 1
- enter details for item 1 -
name > Jet Pack
price > a million bucks
-> invalid answer format for type Double
-> please try again!
price > 1234.23343434
quantity > a lot
-> invalid answer format for type Integer
-> please try again!
quantity > 10

~>