2017-05-04 3 views
0

내 코드는 파일을 읽고 쓰지만 모든 값에 대해 새 줄에 있지 않고 모든 값을 한 줄에 인쇄합니다. 같은 학년으로각 값을 별도의 줄에 추가하는 방법은 무엇입니까?

// 2 points 
static void Q1(String inputFilename, String outputFilename) { 
    // You are given a csv file (inputFilename) with all the data on a single line. Separate the 
    // values by commas and write each value on a separate line in a new file (outputFilename) 

     String data = ""; 
     try { 
      for(String s :Files.readAllLines(Paths.get(inputFilename))){ 
       data = data + s; 
      } 
      Files.write(Paths.get(outputFilename), data.getBytes()); 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 
} 

는 말한다 : 모든

Incorrect on input: [data/oneLine0.csv, output0.txt] 
Expected output : overwrought plastic bomb 
wrapped litter basket 
obstetric matter of law 
diabetic stretching 
spatial marathi 
continental prescott 
reproductive john henry o'hara 
hollow beta blocker 
stereotyped national aeronautics and space administration 
irremediable st. olaf 
brunet fibrosis 
embarrassed dwarf elm 
superficial harrier 
disparaging whetstone 
consecrate agony 
impacted lampoon 
nefarious textile 
some other organisation 
Your output  : overwrought plastic bomb,wrapped litter basket,obstetric matter of law,diabetic stretching,spatial marathi,continental prescott,reproductive john henry o'hara,hollow beta blocker,stereotyped national aeronautics and space administration,irremediable st. olaf,brunet fibrosis,embarrassed dwarf elm,superficial harrier,disparaging whetstone,consecrate agony,impacted lampoon,nefarious textile,some other organisation 

답변

3
String data = ""; 
try { 
    // input file has all data on one line, for loop isn't necessary here 
    // input file has elements separated by comma characters 
    for(String s : Files.readAllLines(Paths.get(inputFilename))){ 
     data = data + s; 
    } 
    String[] separated = data.split(",");// does not handle embedded commas well 
    data = ""; 
    // output file should have each comma separated value on its own line 
    for (String t : separated) { 
     data = data + t + System.getProperty("line.separator"); 
    } 
    Files.write(Paths.get(outputFilename), data.getBytes()); 
} 
: 그래서, 당신이 코드를 얻을 수 s += "\n"; 추가해야
3

첫째, 당신은 CSV 파일에서 쉼표를 제거해야합니다.
s = s.replace(",",""); 또한 사용하려면 각 줄에 \n을 추가하여 새 줄에 표시해야합니다.

// 2 points 
static void Q1(String inputFilename, String outputFilename) { 
// You are given a csv file (inputFilename) with all the data on a single line. Separate the 
// values by commas and write each value on a separate line in a new file (outputFilename) 

    String data = ""; 
    try { 
     for(String s :Files.readAllLines(Paths.get(inputFilename))){ 
      s.replace(",",""); 
      s += "\n"; 
      data = data + s; 
     } 
     Files.write(Paths.get(outputFilename), data.getBytes()); 
    } catch (IOException e) { 

     e.printStackTrace(); 
    } 
} 
관련 문제