I want to print 2D array to txt file on my desktop. It is important, that the output is formatted in way, that is in code, because it represents rows and seats.
Code:
package vaja15;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Vaja15
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Vnesi velikost dvorane (vrste/sedezi): ");
Scanner sc = new Scanner(System.in);
Random r = new Random();
int vrst = sc.nextInt();
int sedezev = sc.nextInt();
int [][] dvorana = new int [vrst][sedezev];
File file = new File ("C:/users/mr/desktop/dvorana.txt");
for(int i = 0; i<dvorana.length; i++)
{
System.out.println();
for (int j = 0; j<dvorana.length; j++)
{
dvorana [i][j] = r.nextInt(3);
System.out.print(dvorana[i][j]);
PrintWriter out = new PrintWriter(file);
out.println(dvorana[i][j]);
out.close();
}
}
}
}
You should not open and close a file in your loop: open a file before the loop, write your array, close the file. Otherwise it will overwrite the file over and over again.
Try this:
PrintWriter out = new PrintWriter(file);
for(int i = 0; i<vrst; i++)
{
System.out.println();
out.println();
for (int j = 0; j<sedezev; j++)
{
dvorana [i][j] = r.nextInt(3);
System.out.print(dvorana[i][j]);
out.print(dvorana[i][j]);
}
}
out.close();
Try the following idea:
try {
File file = new File(path);
FileWriter writer = new FileWriter(file);
BufferedWriter output = new BufferedWriter(writer);
for (int[] array : matrix) {
for (int item : array) {
output.write(item);
output.write(" ");
}
output.write("\n");
}
output.close();
} catch (IOException e) {
}
Related
So I'm trying to use the BufferedWriter Class to create and write to a text file. However, a file is never created, nor is any error generater. However, if I create a text file and specify its path, it will write to that file; it seems that it just doesn't create files. Any suggestions? Thanks in advance.
public class test3 {
public static void main(String[] args) throws IOException {
int ctr = 1;
int count = 10;
Random r = new Random();
String[] textData = new String[count*3];
String storeFile = "testComplete";
String fn = "C:\\Users\\13023\\eclipse-workspace\\test\\src\\testprac\\" + storeFile;
for (int i = 0; i < count*3; i++) {
textData[i] = "Test";
textData[i+1] = "Tes";
textData[i+2] = "T";
ctr++;
i = i + 2;
}
BufferedWriter BW = new BufferedWriter(new FileWriter(fn));
int j = 0;
for (String s: textData) {
BW.write(textData[j] + "\n");
System.out.println("done");
}
BW.close();
}
}
Made a few changes to the code you provided.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class test3 {
public static void main(String[] args) throws IOException {
int ctr = 1;
int count = 10;
// Random r = new Random(); // not used by program, maybe it will later
String[] textData = new String[count*3];
String storeFile = "testCompletetest";
String fn = "C:\\Users\\13023\\eclipse-workspace\\test\\src\\testprac\\" + storeFile;
for (int i = 0; i < count*3; i += 3) {
textData[i] = "Test";
textData[i+1] = "Tes";
textData[i+2] = "T";
ctr++;
// i = i + 2; //<<
}
BufferedWriter BW = new BufferedWriter(new FileWriter(fn));
//int j = 0; not used.
for (String s: textData) {
// ******* modified *******
BW.write(s); // textData[j] + "\n"); write the strings in the array
}
BW.close();
System.out.println("done");
}
I have the following problem I want to read a file and shift each letter down by 3 positions in the alphabet. The caesar cipher works correctly and I can print it, but whenever I am trying to pass it on to a new file with PrintWriter the file remains empty.
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public static char[] encrypt (int offset, char [] charArray) {
char [] cryptArray = new char [charArray.length];
for (int i = 0; i < charArray.length; i++) {
int crypt = (charArray[i] + offset);
cryptArray[i] = (char) (crypt);
}
return cryptArray;
}
public static void main(String[] args) {
String text = "";
StringBuilder convert = new StringBuilder();
try {
File file = new File ("C:\\PATH\\file.txt");
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
text = input.nextLine();
convert = new StringBuilder (text);
char [] arr = text.toCharArray();
char [] newArr = encrypt(3, arr);
for (int i = 0; i < newArr.length; i++) {
convert.append(newArr[i]).toString();
}
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// write file
File outFile = new File ("C:\\PATH\\newfile.txt");
PrintWriter printer = new PrintWriter (outFile);
printer.print(convert);
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
remove convert = new StringBuilder (text); in your loop. It's overwriting your data in the previous loop
Here is the CSV file I am using:
B00123,55
B00783,35
B00898,67
I need to read and store the first value entered in the file e.g. B00123 and store it into an array. A user can add to the file so it is not a fixed number of records.
So far, I have tried this code:
public class ArrayReader
{
static String xStrPath;
static double[][] myArray;
static void setUpMyCSVArray()
{
myArray = new double [4][5];
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "src\\marks.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] InArray = InputLine.split(",");
//copy the content of the inArray to the myArray
for (int x = 0; x < myArray.length; x++)
{
myArray[Rowc][x] = Double.parseDouble(InArray[x]);
}
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (int Rowc = 0; Rowc < 1; Rowc++)
{
for (int Colc = 0; Colc < 5; Colc++)
{
System.out.println(myArray[Rowc][Colc] + " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
This loops round the file but doesn't not populate the array with any data. The outcome is:
****** Setup Array ******
[[D#42a57993
0.0
0.0
0.0
0.0
0.0
There is actually a NumberFormatException happening when in the first row when trying to convert the ID to Double. So I revised the program and it works for me.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ArrayReader
{
static String xStrPath;
static Map<String,Double> myArray = new HashMap<>();
static void setUpMyCSVArray()
{
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "/Users/admin/Downloads/mark.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] inArray = InputLine.split(",");
//copy the content of the inArray to the myArray
myArray.put(inArray[0], Double.valueOf(inArray[1]));
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
System.out.println(e);
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (String key : myArray.keySet()) {
System.out.println(key + " = " + myArray.get(key));
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
Output:
the code can't reader anything ,you file path incorrect.give it absoulte file path.
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
I use opencsv library to read from csv.
import com.opencsv.CSVReader;
public class CSV {
private static String file = <filepath>;
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
list.add(line[0]);
}
Object[] myArray = list.toArray();
System.out.println(myArray.length);
System.out.println(myArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output printed as below
3
B00123
Okay, so I'm not totally sure I'm using arrays correctly or not, but here goes. I have a homework assignment and I'm trying to read from an input file and write to an output file using arrays. I have to show the high temperatures and low temperatures and find the averages for each day of the week. The problem I'm having right now is that nothing is being written to the output file.
Here is what I have so far.
package dowtemps;
import java.util.Arrays;
public class DOWTemps
{
public static void main(String[] args)
{
int index = 0;
int temp = 0;
int dow = 0;
int[] lowTempArray = new int[8];
int[] highTempArray = new int[8];
int[] countArray = new int[8];
int[] totalArray = new int[8];
InputFile in = new InputFile("input.txt");
OutputFile out = new OutputFile("output.txt");
System.out.println("DOW Temperature Started. Please Wait....");
for (index = 0; index < 8; index++)
{
lowTempArray[index] = 999;
highTempArray[index] = -999;
countArray[index] = 0;
totalArray[index] = 0;
dow++;
}
System.out.println(Arrays.toString(lowTempArray));
System.out.println(Arrays.toString(highTempArray));
while (!in.eof())
{
//read in records
dow = in.readInt();
temp = in.readInt();
//load arrays
lowTempArray[dow] = temp;
highTempArray[dow] = temp;
if (temp > highTempArray[dow])
{
highTempArray[dow] = temp;
}
else
{
lowTempArray[dow] = temp;
}
totalArray[dow] = totalArray[dow] + temp;
countArray[dow]++;
//write records
out.writeInt(dow);
out.writeInt(lowTempArray[dow]);
out.writeInt(highTempArray[dow]);
out.writeInt(totalArray[dow]);
out.writeInt(countArray[dow]);
out.writeInt((totalArray[dow] / (countArray[dow])));
out.writeEOL();
}
System.out.println(Arrays.toString(lowTempArray));
System.out.println(Arrays.toString(highTempArray));
System.out.println("DOW Temperature Completed Successfully.");
out.close();
}
}
Maybe you can change InputFile and OutFile for this:
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt", "UTF-8");
I did a little changes on your code, now it read and print.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Scanner;
public class DOWTemps
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException
{
int index = 0;
int temp = 0;
int dow = 0;
int[] lowTempArray = new int[8];
int[] highTempArray = new int[8];
int[] countArray = new int[8];
int[] totalArray = new int[8];
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt", "UTF-8");
System.out.println("DOW Temperature Started. Please Wait....");
for (index = 0; index < 8; index++)
{
lowTempArray[index] = 999;
highTempArray[index] = -999;
countArray[index] = 0;
totalArray[index] = 0;
dow++;
}
System.out.println(Arrays.toString(lowTempArray));
System.out.println(Arrays.toString(highTempArray));
while (in.hasNextLine())
{
//read in records
dow = in.nextInt();
temp = in.nextInt();
//load arrays
lowTempArray[dow] = temp;
highTempArray[dow] = temp;
if (temp > highTempArray[dow])
{
highTempArray[dow] = temp;
}
else
{
lowTempArray[dow] = temp;
}
totalArray[dow] = totalArray[dow] + temp;
countArray[dow]++;
//write records
out.println(dow);
out.println(lowTempArray[dow]);
out.println(highTempArray[dow]);
out.println(totalArray[dow]);
out.println(countArray[dow]);
out.println((totalArray[dow] / (countArray[dow])));
out.println();
}
System.out.println(Arrays.toString(lowTempArray));
System.out.println(Arrays.toString(highTempArray));
System.out.println("DOW Temperature Completed Successfully.");
out.close();
}
}
Just check the logic of your program if its what you need
I previously asked a question about converting a CSV file to 2D array in java. I completely rewrote my code and it is almost reworking. The only problem I am having now is that it is printing backwards. In other words, the columns are printing where the rows should be and vice versa. Here is my code:
int [][] board = new int [25][25];
String line = null;
BufferedReader stream = null;
ArrayList <String> csvData = new ArrayList <String>();
stream = new BufferedReader(new FileReader(fileName));
while ((line = stream.readLine()) != null) {
String[] splitted = line.split(",");
ArrayList<String> dataLine = new ArrayList<String>(splitted.length);
for (String data : splitted)
dataLine.add(data);
csvData.addAll(dataLine);
}
int [] number = new int [csvData.size()];
for(int z = 0; z < csvData.size(); z++)
{
number[z] = Integer.parseInt(csvData.get(z));
}
for(int q = 0; q < number.length; q++)
{
System.out.println(number[q]);
}
for(int i = 0; i< number.length; i++)
{
System.out.println(number[i]);
}
for(int i=0; i<25;i++)
{
for(int j=0;j<25;j++)
{
board[i][j] = number[(j*25) + i];
}
}
Basically, the 2D array is supposed to have 25 rows and 25 columns. When reading the CSV file in, I saved it into a String ArrayList then I converted that into a single dimension int array. Any input would be appreciated. Thanks
so you want to read a CSV file in java , then you might wanna use OPEN CSV
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CsvFileReader {
public static void main(String[] args) {
try {
System.out.println("\n**** readLineByLineExample ****");
String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] col = null;
while ((col = csvReader.readNext()) != null)
{
System.out.println(col[0] );
//System.out.println(col[0]);
}
csvReader.close();
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae+" : error here");
}catch (FileNotFoundException e)
{
System.out.println("asd");
e.printStackTrace();
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
}
}
and you can get the related jar file from here