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
}
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");
}
Below java code is to split a big .csv file into multiple .csv files. But how to store Header in all splitted files?
import java.io.*;
import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class split {
public static void main(String args[]) {
try {
String inputfile = "E:/Sumit/csv-splitting-2/Proposal_Details__c.csv";
System.out.println("Input Path is :- " + inputfile);
double nol = 100000.0;
File file = new File(inputfile);
Scanner scanner = new Scanner(file);
int count = 0;
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
System.out.println("Lines in the file: " + count);
double temp = (count / nol);
int temp1 = (int) temp;
int nof = 0;
if (temp1 == temp) {
nof = temp1;
} else {
nof = temp1 + 1;
}
System.out.println("No. of files to be generated :" + nof);
FileInputStream fstream = new FileInputStream(inputfile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
for (int j = 1; j <= nof; j++) {
String outputpath = "E:/Sumit/csv-splitting-2/";
String outputfile = "File-2-Proposal_Details__c" + j + ".csv";
System.out.println(outputpath + outputfile);
FileWriter fstream1 = new FileWriter(outputpath + outputfile);
BufferedWriter out = new BufferedWriter(fstream1);
for (int i = 1; i <= nol; i++) {
strLine = br.readLine();
if (strLine != null) {
out.write(strLine);
if (i != nol) {
out.newLine();
}
}
}
out.close();
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Assuming your first line is the header, you can have a String header; that will get the read of the first line, eg: header = br.readLine();.
On your for loop for nof (which I assume means number_of_files), you always add the header as the first line when you create a new file.
It would be something like this:
before your for-loop, you just save the header on a variable
String header = br.readLine();
you have 2 for-loops, one that creates a file, the other one that write each line to the newly created file
Inside the first for loop, right after you create the file, you just write the header to it: our.write(header);
General tips:
use variable names that makes sense. nol, nof, j... none of them make sense, you can pretty much call them numOfLines, numOfFiles and currentFile for example.
I have a task to read a text file with several lines, after that I need to count every character's UNICODE value, so the sum of "hello" is 532 and for "how are you" is 1059 and so on, every string begins on new line in the .txt document and so far so good.
But for every line I need to print only its own value, and the way my code works, it adds every line's value and I cant get my head around a way to stop it when the end of the lxtine comes so it looks something like:
*read line
*count char values
*add up
*print them
*start over for the next line, and so
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.String;
import java.util.Arrays;
public class SumLines {
public static void main(String[] args) {
String filePath = "/home/lines.txt";
String readLine;
int sum = 0;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
while ((readLine = bufferedReader.readLine()) != null) {
char[] array = new char[readLine.length()];
System.out.println(readLine);
for (int i = 0; i < readLine.length(); i++) {
Arrays.fill(array, readLine.trim().charAt(i));
sum += (int) array[i];
System.out.print(sum + " ");
}
}
} catch (IOException e) {
System.out.println("Error.\n Invalid or missing file.");
e.printStackTrace();
}
System.out.println("\n*** final " + sum);
}
}
If I understood correctly, for the input:
hello
how are you
You would like to get something like this as output:
hello 532
how are you 1059
*** final 1591
For this, you need to make some modifications to your code:
In addition to calculating the sum of characters values per line, keep another sum of the total of all lines
For each input line, print the line followed by the sum of character values
You don't need an array at all
It's better to trim the input line once, instead of for every character
Like this:
int total = 0;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
String trimmed = readLine.trim();
int sum = 0;
for (int i = 0; i < trimmed.length(); i++) {
sum += (int) trimmed.charAt(i);
}
System.out.println(readLine + " " + sum);
total += sum;
}
} catch (IOException e) {
System.out.println("Error.\n Invalid or missing file.");
e.printStackTrace();
}
System.out.println("\n*** final " + total);
After your for loop, set sum to 0. If you want to print the total sum, then you need another variable, say t.
Like this:
for (int i = 0; i < readLine.length(); i++) {
Arrays.fill(array, readLine.trim().charAt(i));
sum += (int) array[i];
System.out.print(sum + " ");
}
t=t+sum;
sum=0;
Then print t at the end.
A simple solution would be to limit the scope of the sum variable. That way, values will not persist between runs:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.String;
import java.util.Arrays;
public class SumLines {
public static void main(String[] args) {
String filePath = "/home/lines.txt";
String readLine;
int totalSum = 0;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
int sum = 0;
for (int i = 0; i < readLine.length(); i++) {
sum += (int) readLine.charAt(i);
}
System.out.println(readLine + ": " + sum);
totalSum += sum;
}
} catch (IOException e) {
System.out.println("Error.\n Invalid or missing file.");
e.printStackTrace();
}
System.out.println("\n*** final " + totalSum);
}
}
Also, you don't have to use such complicated stuff just to get the Unicode value of a char. I made some improvements.
Have two variables, one for final sum and one for line sum.
public class SumLines {
public static void main(String[] args) {
String filePath = "/home/lines.txt";
String readLine;
int totalSum = 0;
int lineSum = 0
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
while ((readLine = bufferedReader.readLine()) != null) {
char[] array = new char[readLine.length()];
System.out.println(readLine);
for (int i = 0; i < readLine.length(); i++) {
Arrays.fill(array, readLine.trim().charAt(i));
lineSum += (int) array[i];
System.out.print(lineSum + " ");
}
totalSum += lineSum + totalSum;
lineSum = 0;
}
} catch (IOException e) {
System.out.println("Error.\n Invalid or missing file.");
e.printStackTrace();
}
System.out.println("\n*** final " + totalSum);
}
}
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) {
}
I was trying to read from one file and write the bytes read to another file using the classes specified in the title.I successfully did it but while i was trying to try different things i came across a problem which i do not understand.
Here is the code
import java.io.*;
public class FileInputStreamDemo {
public static void main(String[] args)
throws Exception {
// TODO Auto-generated method stub
int size;
InputStream f = new
FileInputStream("G:/Eclipse Workspace/FileInputStream Demo/src/FileInputStreamDemo.java");
System.out.println("Total available bytes: " + (size = f.available()));
/*int n=size/40;
System.out.println("first " + n + " bytes of file one read() at a time");
for (int i=0;i<n;i++)
{
System.out.print((char) f.read());
}
System.out.println("\n Still available: " + f.available());
System.out.println("reading the next" + n + "with one read(b[])");
byte b[] = new byte[n]; */
/*for(int i=0;i<size;i++)
{
System.out.print((char) f.read());
}*/
OutputStream f1 = new
FileOutputStream("G:/Eclipse Workspace/FileInputStream Demo/test.txt");
for (int count = 0; count < size; count++) {
f1.write(f.read());
}
for (int i = 0; i < size; i++) {
System.out.print(f.read());
}
f.close();
f1.close();
}
}
The problem that i am talking about is that when i first read from the FileInputStream object f i.e f.read() and write it to the f1 i.e FileOutputStream object it goes on to do what it is meant to do ,but when i try to read it again it returns -1. why so ?
Use RandomAccessFile and seek(0) method to come back at the beginning.
RandomAccessFile file = new RandomAccessFile(new File("G:/Eclipse Workspace/FileInputStream Demo/src/FileInputStreamDemo.java"), "r");
Here is sample code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
public class FileInputStreamDemo {
public static void main(String[] args) throws Exception {
long size;
File file = new File("D:/Workspace/JavaProject/src/com/test/FileInputStreamDemo.java");
RandomAccessFile f = new RandomAccessFile(file, "r");
System.out.println("Total available bytes: " + (size = file.length()));
OutputStream f1 = new FileOutputStream(new File(
"D:/Workspace/JavaProject/resources/test.txt"));
for (int count = 0; count < size; count++) {
f1.write(f.read());
}
f.seek(0);
for (int i = 0; i < size; i++) {
System.out.print((char)f.read());
}
f.close();
f1.close();
}
}