Как написать CSV-файл в "Groovy" с несколькими строками и без заголовка (ожидается, чтобы избежать добавления) в нем? - PullRequest
0 голосов
/ 25 мая 2019
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 голосов
/ 25 мая 2019

Следующий код:

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

~>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...