Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PLEASE write and read files using try{ String filename = \"src/test.txt\"; for(S

ID: 3809385 • Letter: P

Question

PLEASE write and read files using try{
        String filename = "src/test.txt";
        for(String line : Files.readAllLines(Paths.get(filename))){
            System.out.println(line);
        }
    } catch (IOException ex){
        ex.printStackTrace();
    }
and

try{
            String filename = "src/example.txt";
            String textToWrite = "This will be written to the file";
            Files.write(Paths.get(filename), textToWrite.getBytes());
        }catch(IOException ex){
            ex.printStackTrace();
        }

Files.write(Paths.get(filename), textToWrite.getBytes(), StandardOpenOption.APPEND);

String allValues = "2016-12-06,109.949997,26075900";
    String[] data = allValues.split(",");

PLEASE answer the following JAVA question

Q)

    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)

    }

Explanation / Answer

StringQ1.java

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


public class StringQ1 {

  
   public static void main(String[] args) {
       String inputFilename = "D:\csv.csv";
       String outputFilename = "D:\output.txt";
       Q1(inputFilename,outputFilename );
       System.out.println("Data has been written to file");

   }
   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)
       try{
           Charset charset = Charset.forName("ISO-8859-1");
  
           for(String line : Files.readAllLines(Paths.get(inputFilename),charset)){
   String textToWrite = line;
   String[] data = textToWrite.split(",");
   for(int i=0; i<data.length; i++ ){
   Files.write(Paths.get(outputFilename), (data[i]+" ").getBytes(), StandardOpenOption.APPEND);
   }
           }

}catch(IOException ex){
ex.printStackTrace();
}
   }
}

Output:

csv.csv

1RW,800,64,22,1,48:2,true

output.txt

1RW
800
64
22
1
48:2
true

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote