Writing to file with Java - java
I am trying to write a simple method to save my document to a file (overwriting any previous contents of the file.) Unfortunately, my implementation does not seem to work. I am calling it on my document, which is, for all intents and purposes, an array of String. What I'd like to do is to write the contents of my array, with a separate line for each value in the array, the value in position [0] on the first line, and the value for [1] on the second. How would I go about this ?
This is my implementation so far :
public void save()
{
try
{
PrintWriter outputFile =
new PrintWriter(new BufferedWriter(new FileWriter(docName)));
int lineNo = 1;
while (lineNo != lineNo) // CHANGE THIS!!!
{ outputFile.println(" ~ ");
lineNo++;
}
outputFile.flush();
}
catch (Exception e)
{
System.out.println("Document: Touble writing to "+docName);
System.exit(1);
}
}
If a is an array of strings,
for (String s : a)
outputFile.println(s);
will print the array line-by-line to outputFile.
Iterator over the array, and write the current element.
String document[] = {"String1","String2","String3"};
PrintWriter outputFile =
new PrintWriter(new BufferedWriter(new FileWriter(docName)));
int lineNo = 1;
for(int i = 0; i < document.length; i++)
{ outputFile.println(document[i]);
lineNo++;
}
// myDoc is the "array of string"
foreach (String line : myDoc) {
outputFile.println(line);
}
I might write it more like this:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
/**
* FileDemo
* #author Michael
* #since 2/26/11
*/
public class FileDemo
{
public static void main(String[] args)
{
try
{
FileDemo fd = new FileDemo();
fd.save("out/test.txt", args);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public void save(String filePath, String [] lines) throws FileNotFoundException
{
PrintStream ps = null;
try
{
ps = new PrintStream(new FileOutputStream(filePath));
int lineNum = 1;
for (String line : lines)
{
ps.printf("%5d %s\n", lineNum++, line);
}
}
finally
{
close(ps);
}
}
public static void close(PrintStream ps)
{
if (ps != null)
{
ps.flush();
ps.close();
}
}
}
I didn't see any actual content in your code, so I added some. I didn't how a file with line numbers was very interesting. You'd be able to modify this to make it differently if you wish.
Related
Indexing through an array to return any specific value in java
So, I have created code which is reading a CSV file line by line, then splitting each line into their individual values then putting this into an array, but i am stuck on trying the index a value from this array I have created, I will attach the CSV file and also my code, and lets say for example how would I access the value at [3,4], which should be Andorra, and [6,6] which should be 17? CSV FILE: Date,iso3,Continent,CountryName,lat,lon,CumulativePositive,CumulativeDeceased,CumulativeRecovered,CurrentlyPositive,Hospitalized,IntensiveCare,NUTS 31/1/2021,AFG,AS,Afghanistan,33.930445,67.678945,55023,2400,,52623,,,AF 31/1/2021,ALB,EU,Albania,41.156986,20.181222,78127,1380,47424,29323,324,19,AL 31/1/2021,DZA,AF,Algeria,28.026875,1.65284,107122,2888,,104234,,,DZ 31/1/2021,AND,EU,Andorra,42.542268,1.596865,9937,101,,9836,44,,AD 31/1/2021,AGO,AF,Angola,-11.209451,17.880669,19782,464,,19318,,,AO 31/1/2021,AIA,NA,Anguilla,18.225119,-63.07213,17,0,,17,,,AI 31/1/2021,ATG,NA,Antigua and Barbuda,17.363183,-61.789423,218,7,,211,,,AG 31/1/2021,ARG,SA,Argentina,-38.421295,-63.587403,1915362,47775,,1867587,,,AR 31/1/2021,ARM,AS,Armenia,40.066181,45.111108,167026,3080,,163946,,,AM 31/1/2021,ABW,NA,Aruba,12.517713,-69.965112,6858,58,,6800,,,AW 31/1/2021,AUS,OC,Australia,-26.853388,133.275154,28806,909,,27897,,,AU 31/1/2021,AUT,EU,Austria,47.697542,13.349319,411921,7850,383158,21058,1387,297,AT 31/1/2021,AZE,AS,Azerbaijan,40.147396,47.572098,229935,3119,,226816,,,AZ 31/1/2021,BHS,NA,Bahamas,24.885993,-76.709892,8174,176,,7998,,,BS 31/1/2021,BHR,AS,Bahrain,26.039722,50.559306,102626,372,,102254,,,BH 31/1/2021,BGD,AS,Bangladesh,23.68764,90.351002,535139,8127,,527012,,,BD 31/1/2021,BRB,NA,Barbados,13.18355,-59.534649,1498,12,,1486,,,BB 31/1/2021,BLR,EU,Belarus,53.711111,27.973847,248336,1718,,246618,,,BY 31/1/2021,BEL,EU,Belgium,50.499527,4.475402,711417,21118,,690299,1788,315,BE 31/1/2021,BLZ,NA,Belize,17.192929,-88.5009,11877,301,,11576,,,BZ 31/1/2021,BEN,AF,Benin,9.322048,2.313138,3786,48,,3738,,,BJ 31/1/2021,BMU,NA,Bermuda,32.320236,-64.774022,691,12,,679,,,BM 31/1/2021,BTN,AS,Bhutan,27.515709,90.442455,859,1,,858,,,BT 31/1/2021,BWA,AF,Botswana,-22.344029,24.680158,21293,134,,21159,,,BW 31/1/2021,BRA,SA,Brazil,-14.242915,-53.189267,9118513,222666,,8895847,,,BR 31/1/2021,VGB,NA,British Virgin Islands,18.573601,-64.492065,141,1,,140,,,VG CODE: public static String readFile(String file) { FileInputStream fileStream = null; InputStreamReader isr; BufferedReader bufRdr; int lineNum; String line = null; try { fileStream = new FileInputStream(file); isr = new InputStreamReader(fileStream); bufRdr = new BufferedReader(isr); lineNum = 0; line = bufRdr.readLine(); while ((line != null) && lineNum < 27) { lineNum++; System.out.println(line); line = bufRdr.readLine(); } fileStream.close(); } catch (IOException e) { if (fileStream != null) { try { fileStream.close(); } catch (IOException ex2) { } } System.out.println("Error: " + e.getMessage()); } return line; } private static void processLine(String line) { String[] splitLine; splitLine = line.split(","); int lineLength = splitLine.length; for (int i = 0; i < lineLength; i++) { System.out.print(splitLine[i] + " "); } System.out.println(""); }
You need to create a 2D array in readFile. As the file is read, and and each line is split by processLine, insert the array into the 2D array. The method readFile at the end returns the 2D array. Make processLine to return a string array and have it return the result of the split. I marked where I made changes to your code. import java.io.*; public class Main { public static void main(String[] args){ String[][] data = readFile("data.txt"); System.out.println(data[3][4]); System.out.println(data[6][6]); } public static String[][] readFile(String file) { //<<< changed FileInputStream fileStream = null; InputStreamReader isr; BufferedReader bufRdr; int lineNum; String line = null; String[][] data = new String[28][]; //<<< added try { fileStream = new FileInputStream(file); isr = new InputStreamReader(fileStream); bufRdr = new BufferedReader(isr); lineNum = 0; line = bufRdr.readLine(); while (lineNum < 27) { // <<< changed System.out.println(line); line = bufRdr.readLine(); if (line == null) break; // <<< added data[lineNum++] = processLine(line); // <<< added } fileStream.close(); } catch (IOException e) { if (fileStream != null) { try { fileStream.close(); } catch (IOException ex2) { } } System.out.println("Error: " + e.getMessage()); } return data; //added } private static String[] processLine(String line) { //<< changed String[] splitLine; splitLine = line.split(","); int lineLength = splitLine.length; for (int i = 0; i < lineLength; i++) { System.out.print(splitLine[i] + " "); } System.out.println(""); return splitLine; // <<< added } }
You can do it quite simply using the stream API. import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Collectors; import java.util.stream.Stream; public class CsvTest0 { public static void main(String[] args) { Path path = Paths.get("geografy.csv"); try (Stream<String> lines = Files.lines(path)) { String[][] arr = lines.skip(1L) .limit(27L) .map(l -> l.split(",")) .collect(Collectors.toList()) .toArray(new String[][]{}); System.out.println(arr[3][3]); System.out.println(arr[5][6]); } catch (IOException xIo) { xIo.printStackTrace(); } } } However, regarding the code in your question, below is a fixed version followed by notes and explanations. import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CsvTest1 { public static String[][] readFile(String file) throws IOException { Path path = Paths.get(file); String[][] arr = new String[27][]; int lineNum; String line = null; try (BufferedReader bufRdr = Files.newBufferedReader(path)) { lineNum = 0; line = bufRdr.readLine(); // Ignore first line of file since it contains headings only. line = bufRdr.readLine(); while ((line != null) && lineNum < 27) { arr[lineNum++] = processLine(line); line = bufRdr.readLine(); } } return arr; } private static String[] processLine(String line) { return line.split(","); } public static void main(String[] args) { try { String[][] arr = readFile("geografy.csv"); System.out.println(arr[3][3]); System.out.println(arr[5][6]); } catch (IOException x) { x.printStackTrace(); } } } Note that the below is not in any particular order. I wrote them as they came to me. No need for FileInputStream and InputStreamReader in order to create BufferedReader. Use Files class instead. Close files in a finally block and not in a catch block. Hence use try-with-resources. I believe better to propagate the exception to the calling method, i.e. method main in this case. I also believe that, unless you can safely ignore the exception, it is always beneficial to print the stack trace. You don't want to process the first line of the file. You appear to have your array indexes mixed up. According to sample data, Andorra is row 3 and column 3 (not column 4). Also, 17 is at [5][6] and not [6][6]. Two-dimensional arrays in java can be declared with only one dimension indicated. Since you only want first 27 lines of file, you know how many rows will be in the 2D array.
Problem converting .dat file to .csv file
I'm trying to convert .dat file to csv file but I have a problem with it. Below is my code: public class Main { public static void main(String[] args) { DatToCsv dataToCsv = new DatToCsvImpl(); //creating object of DataToCsvImpl class try { // Three parameter should be giving to convertDatToCsv function namely input file location and output file // location and fixed column size respectively dataToCsv.convertDatToCsv("testing.dat", "testing.csv", 5); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Code 2: public interface DatToCsv { public void convertDatToCsv(String datFileLocation,String outputFile, int column)throws IOException; } Code 3: import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class DatToCsvImpl implements DatToCsv { #Override public void convertDatToCsv(String datFileLocation, String outputFile, int column) throws IOException { // creating instance of file writer, buffer reader and writer String st; FileWriter writer; BufferedWriter bw; BufferedReader br; String csvData = ""; int count = 0; try { File file = new File(datFileLocation); // .dat file location writer = new FileWriter(outputFile); // .csv file location bw = new BufferedWriter(writer); // giving writer to buffer writer constructor to initilize br = new BufferedReader(new FileReader(file)); // giving input file (.dat) file to buffer reader StringBuilder sb = new StringBuilder(); /* * Using while loop (as long as) upto end of file getting data by line by line */ while ((st = br.readLine()) != null) { /* * replacing multiple space into single space and comma separated of single * space */ st = st.trim().replaceAll(" +", ","); // if first line of file consider to be heading if (count == 0) { csvData = st; } else { csvData = csvData + "," + st; } count++; } // converting all comma seperated value to string array String csvArray[] = csvData.split(","); int runningCount = 1; for (String str : csvArray) { if (runningCount == column) { // compare fixed column size to running count every fixed column size new // line added \n sb.append(str + "\n"); runningCount = 1; } else { sb.append(str + ","); // otherwise comma added at the end of every key runningCount++; } } bw.write(sb.toString()); /* * flush is because if data 1024bytes not it not store to csv file so we need to * explicitly mention push data to csv */ bw.flush(); writer.close(); br.close(); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } For whatever reason it doesnt work and it doesnt accept my input and the output is nowhere to be found. I have tried googling for help to find the input and output but I still couldnt do it. Any help is appreciated thanks
How I can to skip some area of text, when reading file?
I reading a .txt file and want to skip a listing of code in this text, when putting result in StringBuilder. The example of text: The following Bicycle class is one possible implementation of a bicycle: /* The example of Bicycle class class Bicycle { int cadence = 0; int speed = 0; } */ So that's what I could come to: public class Main { public static BufferedReader in; public static StringBuilder stringBuilder = new StringBuilder(); public static void main(String[] args) { String input = "input_text.txt"; try { in = new BufferedReader(new FileReader(input)); } catch (FileNotFoundException e) { e.printStackTrace(); } String inputText; try { while ((inputText = in.readLine()) != null) { if (inputText.startsWith("/*")) { // The problem is there: while (!inputText.endsWith("*/")) { int lengthLine = inputText.length(); in.skip((long)lengthLine); } } stringBuilder.append(inputText); } } catch (IOException e) { e.printStackTrace(); } I got the infinity while loop and can't jump to next line.
You never reset the value of inputText in your while loop, so it will never not end with */ resulting in an infinite loop. Also you don't need to use the skip() method as simply reading the lines until you encounter a */ will work. Try changing your loop to: while (!inputText.endsWith("*/")) { String temp = in.readLine(); if(temp == null) {break;} inputText = temp; } Output: (With printing the StringBuilder) The following Bicycle class is one possible implementation of a bicycle:
Is it possible to create fileIO within a program?
I have a bunch of code that has now evolved into a fully functioning console based (mostly) game. I'm now curious that if I want to implement an Input/Output function do I have to create it in a different file or can I put it in the same class as my code. For instance, an example my lecturer has given for writing a fileIO for saving names is the following: import java.io.*; class savenames { public static void main(String[] params) throws IOException { PrintWriter outputStream = new PrintWriter(new FileWriter("mydata.txt")); // Create an array with some sample names to store String [] names = {"Paul", "Jo", "Mo"}; // Store the names from the array in the file, one name per line for (int i = 0; i < names.length; i++) { outputStream.println(names[i]); } outputStream.close(); System.exit(0); } } This accompanies the following code (in a different file): import java.io.*; class readnames { public static void main(String[] params) throws IOException { BufferedReader inStream = new BufferedReader(new FileReader("mydata.txt")); String [] names = new String[3]; System.out.println("The names in the file mydata.txt are:"); for (int i = 0; i < names.length; i++) { names[i] = inStream.readLine(); System.out.println(names[i]); } inStream.close(); System.exit(0); } } I was just wondering if it would be possible do the two things in the same file, as my code has many different methods and I'm not sure how to make a separate method to do this. Thanks. EDIT: Perhaps I can modify this question to make it a little better. I have the following main method in my boardgame: class newminip { public static void main (String[] params) throws IOException { numberPlayers(); int diceroll = dicethrow(6); int[] scorep1 = scorearrayp1(); questions(diceroll, scorep1); sort(scorep1); System.exit(0); } .... insert code here .... public static void exitmethod(int[] scorep1) { sort(scorep1); for (int i = 0; i < 4; i++) { System.out.println("Player " + (i+1) + " scored " + scorep1[i] + ""); } System.exit(0); } } //END class And I want something that will save the scores into a new text file. I hope this had made it a tiny bit clearer.
Yes you could do it in one file. I have created a new class for it: import java.io.*; import java.util.ArrayList; public class FileIO { public static String[] readStringsFromFile(final String filename) throws IOException { BufferedReader inStream = new BufferedReader(new FileReader(filename)); //Use ArrayList since you don't know how many lines there are in the file ArrayList<String> lines = new ArrayList<String>(); String line; //Read until you reach the end of the file while ((line = inStream.readLine()) != null) { lines.add(line); } inStream.close(); //Convert it back to a string array return lines.toArray(new String[lines.size()]); } public static void writeStringsToFile(String[] lines, final String filename) throws IOException { PrintWriter outputStream = new PrintWriter(new FileWriter(filename)); for (int i = 0; i < lines.length; i++) { outputStream.println(lines[i]); } outputStream.close(); } public static void main(String[] args) { //To test the methods: //Create an array to write to the file String[] linesToWrite = {"firstLine", "secondLine", "thirdLine"}; try { //Write the strings to a file named "testfile.txt" writeStringsToFile(linesToWrite, "testfile.txt"); //Read all lines of a file named "testfile.txt" String[] readLines = readStringsFromFile("testfile.txt"); //Print out the read lines for (String line : readLines) { System.out.println(line); } } catch (IOException e) { System.err.println("Error msg"); } } } The main method in this case is just to test, you can remove it and copy the two other methods to your class. This is probably not the best or most efficient way to do file io but in your case this should do the job (: EDIT: So if you just need to read an write integers to a file you could use something like this: import java.io.*; import java.util.ArrayList; public class FileIO { public static Integer[] readIntegersFromFile(final String filename) throws IOException { BufferedReader inStream = new BufferedReader(new FileReader(filename)); //Use ArrayList since you don't know how many lines there are in the file ArrayList<Integer> integers = new ArrayList<Integer>(); String line; //Read until you reach the end of the file while ((line = inStream.readLine()) != null) { //Parse integers form read string values integers.add(Integer.parseInt(line)); } inStream.close(); return integers.toArray(new Integer[integers.size()]); } public static void writeIntegersToFile(Integer[] lines, final String filename) throws IOException { PrintWriter outputStream = new PrintWriter(new FileWriter(filename)); for (int i = 0; i < lines.length; i++) { outputStream.println(lines[i]); } outputStream.close(); } public static void main(String[] args) { //To test the methods: //Create an array to write to the file Integer[] linesToWrite = {1, 100, 15}; try { //Write the strings to a file named "testfile.txt" writeStringsToFile(linesToWrite, "testfile.txt"); //Read all lines of a file named "testfile.txt" Integer[] readLines = readStringsFromFile("testfile.txt"); //Print out the read lines for (int line : readLines) { System.out.println(line); } } catch (IOException e) { System.err.println("Error msg"); } } }
You can create a Java file with the code from both main methods and remove the System.exit(0); as you don't need it. This way one program will do both. I suggest you write the file before attempting to read it. Putting it all in one program make the use of the file rather redundant however, in which case you can just print the array.
How do I remove all occurrences of "," and "[" from the output in java?
Here is my code. The input consists of names of anime(japanese cartoons) which i have stored it in testfile in anime.txt and I am arranging them in alphabetical order and writing it back into another file name animeout.txt. The input file does not contain any comma or square bracket but the output file has it. public class Main { public static ArrayList<String> read(String filePath) throws IOException { ArrayList<String> names = new ArrayList<String>(); BufferedReader reader = new BufferedReader(new FileReader(filePath)); int numRead = 0; String line; while ((line = reader.readLine()) != null) { names.add(line + "\n"); numRead++; } System.out.println("\n\n count " +numRead); reader.close(); System.out.println(names); return names; } public static void write(ArrayList<String> input) throws IOException { File file = new File("Animeout.txt"); file.createNewFile(); FileWriter writer = new FileWriter(file); writer.write(input); writer.flush(); writer.close(); } public static void main(String args[]) throws IOException { ArrayList<String> names2 = new ArrayList<String>(); String path= "anime.txt"; String test; names2 = read(path); Collections.sort(names2, null); // System.out.println(names2); write(names2); } } Input file has about 200 lines. Below is just a small example One piece Naruto/naruto shippuden Bleach Fullmetal alchemist brotherhood Fate/stay night Fairy tale Blue exorcist Soul eater Death note Output file contains , and [ count 105 [11 eyes , A certain magical index , A certain magical index II , Aldnoah.Zero , Angel beats! , Another , Asu no yoichi , Bay blade , Beelzebub , Ben-To
String str = "[12,34,45]"; String out = str.replaceAll(",|\\[|\\]",""); output: 123445
Why are you using a ObjectOuputStream? That is intended for when you want to serialise Java objects and restore them later. I don't see why you need it here. Just use a FileWriter, like so: public static void write(ArrayList<String> input) throws IOException { try { File file = new File("Animeout.txt"); FileWriter fw = new FileWriter(file); for (int i = 0; i < input.size(); i++) { fw.append(input.get(i) + "\n"); } } finally { try { if (fw != null) fw.close(); } catch (Exception e) { // ignore } } }
Your write method is unfortunate. Try something like this instead (and remove the + "\n" when reading the lines): public static void write(ArrayList<String> lines) throws IOException { File file = new File("Animeout.txt"); PrintStream ps = null; try { ps = new PrintStream(file); for (final String line : lines) { ps.println(line); } } finally { if (ps != null) { ps.close(); } } } The ObjectOutputStream you are using is not appropriate for simply writing lines of text. Finally, if all you want to do is sorting the lines of a text file, at least on a POSIX system, you can just do it with $ sort anime.txt > Animeout.txt from the command line.