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");
}
Related
I'm trying to create a program that creates a lot of .txt files in the user's desktop, and writing inside of each one something, but it just writes on the first file, it looks like that the second for loop does not work anymore.
Here is my code:
package main;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userHome = System.getProperty("user.home");
String path = userHome + "/Desktop/test.txt";
try {
for (int j = 0; j < 10; j++) {
BufferedWriter br = new BufferedWriter(new FileWriter(userHome + "/Desktop/test" + j + ".txt"));
for (int i = 0; i < 10; i++) {
br.write(i);
br.newLine();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
bw.write(i); this does not print the numeric value as expected
c - int specifying a character to be written
Ref
So, if you really need the numeric value 0 to 9 to be printed
bw.write(i + 48);
Also, please close the stream with bw.close()
A general note in using readers/writers
Always use writers/readers with an encoding and do not assume UTF-8. It is always better to explicitly state the encoding.
Assuming you are using java 11
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
final String userHome = System.getProperty("user.home");
final String path = userHome + "/Desktop/";
for (int j = 0; j < 10; j++) {
final String file = path + "/test" + j + ".txt";
try (final FileWriter fw = new FileWriter(file, StandardCharsets.UTF_8);
final BufferedWriter bw = new BufferedWriter(fw)) {
for (int i = 0; i < 10; i++) {
bw.write(i + 48); // bw.write(String.valueOf(i));
bw.newLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
There are 2 issues in your code.
for (int j = 0; j < 10; j++) {
BufferedWriter br = new BufferedWriter(new FileWriter(userHome + "/Desktop/test" + j + ".txt"));
for (int i = 0; i < 10; i++) {
br.write(String.valueOf(i)); // instead of br.write(i);
br.newLine();
}
br.close(); // close your writer
}
I have to enter string x in reverse order, but it outputs null. Why and how to fix it?
Sorry in advance for the name of the variables, but also for the double loop (I know it's bad, but this is the only thing that came to my mind)
The main question is why null is entered in the file
public static void OutputOfFile(char[] x)throws IOException {
File file = new File("test");
PrintWriter out = new PrintWriter(file.getAbsoluteFile());
out.print(x);
out.close();
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String x = reader.readLine();
char[] x1 = x.toCharArray();
char[] x2 = new char[x1.length];
for(int i = x1.length - 1; i < -1; i--) {
for (int k = 0; k > x1.length; k++) {
x2[i] = x1[k];
}
}
OutputOfFile(x2);
}
the problem is with your loop, you need to iterate in one loop instead of an inner loop:
public static void OutputOfFile(char[] x) throws IOException {
File file = new File(""test"");
PrintWriter out = new PrintWriter(file.getAbsoluteFile());
out.print(x);
out.close();
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String x = reader.readLine();
char[] x1 = x.toCharArray();
char[] x2 = new char[x1.length];
for (int i = x1.length - 1, k = 0; i >= 0; i--, k++) {
x2[k] = x1[i];
}
OutputOfFile(x2);
}
I am trying to link two files together and have one count the amount of characters and have the other one give the answer to the character counter. The first file cant have the word that is being given to be displayed as well. How would I go about doing so?
File one
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
System.out.println("Line " + (answer + 1));
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("The specific Line is: " + text);
}
File two
public class countWords
{
public static void main(String[] args) {
String string = "nose";
int count = 0;
//Counts each character except space
string = string.replaceAll(" ", "");
count = string.length();
//Displays the total number of characters present in the given string
System.out.println("Total number of characters in a string: " + count);
}
}
Figured it out for the first file
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
WordCounter wc = new WordCounter(text);
wc.removeSpaces();
wc.count();
int letters = wc.getCount();
System.out.println("The amount of characters is:" + letters);
}
}
Got the second file
public class WordCounter
{
private final String word;
private int count = 0;
public WordCounter(String word) {
this.word = word;
}
public void removeSpaces() {
word.replaceAll(" ", "");
}
public void count() {
count = word.length();
}
public int getCount() {
return count;
}
}
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
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) {
}