I trying to write into the txt file.
But with out losing the data that is already stored in the file.
But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.
My code is:
public void addWorker(Worker worker){
workers.put(worker.getId(), worker);
}
public void printWorker (String id){
Worker work = (Worker) workers.get( id );
if (work == null) {
System.out.println("Worker NOT found");
}
else {
work.printText();
}
}
public void printWorkers() {
if (workers.size() == 0) {
System.out.println("No workres");
return;
}
Collection<Worker> c = workers.values();
Iterator<Worker> itr = c.iterator();
System.out.println("Workers in division "+dName+ ":");
while (itr.hasNext()) {
Worker wo = itr.next();
wo.printText();
}
}
public void writeToFile(){
PrintWriter pw = null;
try{
pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
Collection<Worker> c = workers.values();
Iterator<Worker> itr = c.iterator();
while (itr.hasNext()) {
Worker wo = itr.next();
pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
pw.println();
}
}
catch(Exception e) {
System.out.println(e);
}
finally {
if (pw != null) {
pw.close();
}
}
}
}
Can you help me?
You have to set the Stream to append mode like this:
pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));
Use a FileWriter with second argument 'true' and a BufferedWriter:
FileWriter writer = new FileWriter("outFile.txt", true);
BufferedWriter out = new BufferedWriter(writer);
Create a separate variable to emphasize that, appending to file.
boolean append = true;
pw = new PrintWriter(new FileWriter(new File("filepath.txt"), append));
In Java 7,
Files.write(FileSystems.getDefault().getPath(targetDir,fileName),
strContent.getBytes(),StandardOpenOption.CREATE,StandardOpenOption.APPEND);
Related
public class FileSplitter2 {
public static void main(String[] args) throws IOException {
String filepath = "D:\\temp\\test.txt";
BufferedReader reader = new BufferedReader(new FileReader(filepath));
String strLine;
boolean isFirst = true;
String strGroupByColumnName = "city";
int positionOgHeader = 0;
FileWriter objFileWriter;
Map<String, FileWriter> groupByMap = new HashMap<String, FileWriter>();
while ((strLine = reader.readLine()) != null) {
String[] splitted = strLine.split(",");
if (isFirst) {
isFirst = false;
for (int i = 0; i < splitted.length; i++) {
if (splitted[i].equalsIgnoreCase(strGroupByColumnName)) {
positionOgHeader = i;
break;
}
}
}
String strKey = splitted[positionOgHeader];
if (!groupByMap.containsKey(strKey)) {
groupByMap.put(strKey, new FileWriter("D:/TestExample/" + strKey + ".txt"));
}
FileWriter fileWriter = groupByMap.get(strKey);
fileWriter.write(strLine);
}
for (Map.Entry<String,FileWriter> entry : groupByMap.entrySet()) {
entry.getKey();
}
}
}
This is my code. I am not getting a proper result. The file contains 10 columns, and the 5th column is 'city'. There are 10 different cities in a file. I need to split each city a separate file.
You are not calling close on all the FileWriter and hence the data may not get flushed to the file.
See FileWriter is not writing in to a file
At the end of the processing,
groupByMap.values().forEach(fileWriter -> {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace(); //Add appropriate error handling
}
});
There is a bug in your code. You need to move the statements after the if (isFirst) block into the else block. Else, it will create a city.txt file too.
I have a rather tricky question
Is there a way to check if something has been written into a file?
This is a piece of code written by Eric Petroelje, and I need to check if the "Hello world" has been written into a file.
This would be useful for checking if a big number is written to a text file.
Thank you in advance!
public class Program {
public static void main(String[] args) {
String text = "Hello world";
BufferedWriter output = null;
try {
File file = new File("example.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
output.close();
}
}
}
}
Read the file after having written it
public boolean writeToTXT(String text, String path)
{
BufferedWriter output = null;
try {
File file = new File(path);
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.flush();
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
output.close();
}
}
try(BufferedReader br = new BufferedReader(new FileReader(path))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString().equals(text); }
}
I have a CSV log file and it contains many rows like this:
2016-06-21 12:00:00,000 : helloworld: header1=2;header2=6;header=0
I want to write them to a new CSV file.
public void readLogFile() throws Exception
{
String currentLine = "";
String nextLine = "";
BufferedReader reader = new BufferedReader(new FileReader(file(false)));
while ((currentLine = reader.readLine()) != null)
{
if (currentLine.contains("2016") == true)
{
nextLine = reader.readLine();
if (nextLine.contains("helloworld") == true)
{
currentLine = currentLine.substring(0, 23);
nextLine = nextLine.substring(22, nextLine.length());
String nextBlock = replaceAll(nextLine);
System.out.println(currentLine + " : helloworld: " + nextBlock);
String[] data = nextBlock.split(";");
for (int i = 0, max = data.length; i < max; i++)
{
String[] d = data[i].split("=");
map.put(d[0], d[1]);
}
}
}
}
reader.close();
}
This is my method to write the content:
public void writeContentToCsv() throws Exception
{
FileWriter writer = new FileWriter(".../file_new.csv");
for (Map.Entry<String, String> entry : map.entrySet())
{
writer.append(entry.getKey()).append(";").append(entry.getValue()).append(System.getProperty("line.separator"));
}
writer.close();
}
This is the output I want to have:
header1; header2; header3
2;6;0
1;5;1
5;8;8
...
Currently, the CSV file looks like this (only showing one dataset):
header1;4
header2;0
header3;0
Can anyone help me fix the code?
Create a class to store the header values, and store it in the list.
Iterate over the list to save the results.
The currently used map can only store 2 values (which it is storing the header value (name its corresponding value)
map.put(d[0], d[1]);
here d[0] will be header1 and d[1] will be 4 (but we want only 4 from here)
class Headervalues {
String[] header = new String[3];
}
public void readLogFile() throws Exception
{
List<HeaderValues> list = new ArrayList<>();
String currentLine = "";
BufferedReader reader = new BufferedReader(new FileReader(file(false)));
while ((currentLine = reader.readLine()) != null)
{
if (currentLine.contains("2016") && currentLine.contains("helloworld"))
{
String nextBlock = replaceAll(currentLine.substring(22, currentLine.length());
String[] data = nextBlock.split(";");
HeaderValues headerValues = new HeaderValues();
//Assuming data.length will always be 3.
for (int i = 0, max = data.length; i < max; i++)
{
String[] d = data[i].split("=");
//Assuming split will always have size 2
headerValues.header[i] = d[1];
}
list.add(headerValues)
}
}
}
reader.close();
}
public void writeContentToCsv() throws Exception
{
FileWriter writer = new FileWriter(".../file_new.csv");
for (HeaderValues value : headerValues)
{
writer.append(value.header[0]).append(";").append(value.header[1]).append(";").append(value.header[2]);
}
writer.close();
}
For writing to CSV
public void writeCSV() {
// Delimiter used in CSV file
private static final String NEW_LINE_SEPARATOR = "\n";
// CSV file header
private static final Object[] FILE_HEADER = { "Empoyee Name","Empoyee Code", "In Time", "Out Time", "Duration", "Is Working Day" };
String fileName = "fileName.csv");
List<Objects> objects = new ArrayList<Objects>();
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
// Create the CSVFormat object with "\n" as a record delimiter
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
try {
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);
// Write a new student object list to the CSV file
for (Object object : objects) {
List<String> record = new ArrayList<String>();
record.add(object.getValue1().toString());
record.add(object.getValue2().toString());
record.add(object.getValue3().toString());
csvFilePrinter.printRecord(record);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read and write/append CSV file using org.apache.commons.csv.CSVParser.
public void appendCSV(){
String [] records = {};
String csvWrite= "";
Boolean status = false;
try(BufferedReader csvReaders = new BufferedReader(new FileReader("csvfile.csv"));
CSVParser parser = CSVFormat.DEFAULT.withDelimiter(',').withHeader().parse(csvReaders);
) {
for(CSVRecord record : parser) {
status= record.get("Microservice").equalsIgnoreCase(apipath);
int status_code=0;
String httpMethod = record.get("Method");
if(status==true) {
csvWrite = record.get("apiName")+"-"+record.get("Microservice")+"-"+record.get("R_Data")+"-"+record.get("Method")+"-"+record.get("A_Status")+"-"+400+"-"+record.get("A_Response")+"-"+"{}";
records = csvWrite.split("-");
CSVWriter writer = new CSVWriter(new FileWriter(pathTowritecsv,true));
writer.writeNext(records);
writer.close();
}else {
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
I am trying to concatenate multiple text files. The program is working correctly, but if I do not know the total number of files, then how should the for loop be changed?
public class MultipleMerge {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String inFileName = "C:\\Users\\dokania\\Desktop\\Bio\\Casp10\\fasta\\out";
File file = new File("C:\\Users\\dokania\\Desktop\\New folder\\out.txt");
try {
String s;
int fileCounter = 0;
FileWriter fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
for (fileCounter = 0; fileCounter < 157; fileCounter++) {
br = new BufferedReader(new FileReader(inFileName + (fileCounter++) + ".fa"));
while ((s = br.readLine()) != null) {
bw.write(s + "\n");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Try get an array of Files in directory:
File[] array = new File("C:\\Users\\dokania\\Desktop\\Bio\\Casp10\\fasta\\").listFiles();
And then go through all files using foreach cycle
for(File file:array){
//...
}
Maybe you'll need to use FileFilter:
http://docs.oracle.com/javase/7/docs/api/java/io/FileFilter.html
in method listFiles()
You could use command line arguments:
public class CommandLineTest {
public static void main(String[] args) {
int howManyFiles = Integer.parseInt(args[0]);
}
}
Above code gives you the first command line argument and treats it as an integer. In your code, you should check if there really is an integer specified, though.
/** I have some methods likes add,display,sort,delete,and exit that implemented the ArrayList function. It works correctly, but the problem is that the objects that had been added were not saved on a .txt file, just the temporary objects. So I need to add them into text file,so that I can display and delete them later. Here's the part of the codes.
*/
public class testing {
public static void main(String[] args) {
String Command;
int index = 0;
Scanner input = new Scanner(System.in);
ArrayList<String> MenuArray = new ArrayList<String>();
boolean out = false;
while (!out) {
System.out.print("Enter your Command: ");
Command = input.nextLine();
// method ADD for adding object
if (Command.startsWith("ADD ") || Command.startsWith("add ")) {
MenuArray.add(Command.substring(4).toLowerCase());
// indexing the object
index++;
/** i stuck here,it won't written into input.txt
BufferedWriter writer = new BufferedWriter(new FileWriter(
"input.txt"));
try {
for (String save : MenuArray) {
int i = 0;
writer.write(++i + ". " + save.toString());
writer.write("\n");
}
} finally {
writer.close();
}*/
} else if (Command.startsWith("EXIT") || Comand.startsWith("exit")) {
out = true;
}
}
}
}
FileUtils#writeLines seems to do exactly what you need.
You can use ObjectOutputStream to write an object into a file:
try {
FileOutputStream fos = new FileOutputStream("output");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(MenuArray); // write MenuArray to ObjectOutputStream
oos.close();
} catch(Exception ex) {
ex.printStackTrace();
}