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.
Related
copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
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 one input.txt file which consist on let suppose 520 lines.
I have to make a code in java which will act like this.
Create first file named file-001.txt from first 200 lines. then create another file-002 from 201-400 lines. then file-003.txt from remaining lines.
I have coded this, it just write first 200 lines. What changes I need to make in order to update its working to above scenario.
public class DataMaker {
public static void main(String args[]) throws IOException{
DataMaker dm=new DataMaker();
String file= "D:\\input.txt";
int roll=1;
String rollnum ="file-00"+roll;
String outputfilename="D:\\output\\"+rollnum+".txt";
String urduwords;
String path;
ArrayList<String> where = new ArrayList<String>();
int temp=0;
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
++temp;
if(temp<201){ //may be i need some changes here
dm.filewriter(line+" "+temp+")",outputfilename);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void filewriter(String linetoline,String filename) throws IOException{
BufferedWriter fbw =null;
try{
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(filename, true), "UTF-8");
fbw = new BufferedWriter(writer);
fbw.write(linetoline);
fbw.newLine();
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
fbw.close();
}
}
}
One way can be use of if else but I cant just use it because my actual file is 6000+ lines.
I want this code to work like I run the code and give me 30+ output files.
You can change the following bit:
if(temp<201){ //may be i need some changes here
dm.filewriter(line+" "+temp+")",outputfilename);
}
to this:
dm.filewriter(line, "D:\\output\\file-00" + ((temp/200)+1) + ".txt");
This will make sure first 200 lines go to first file, next 200 lines go to next file and so on.
Also, you might want to batch 200 lines together and write them in one go rather than creating a writer everytime and write to file.
You may have a method that creates the Writer to the current File, reads up to limit number of lines, closes the Writer to the current File, then returns true if it had enough to read , false if it couldn't read the limit number of lines (i.e, abort next call, don't attempt to read more lines or write next file).
Then you would call this in a loop , passing the Reader, the new file name, and the limit number.
Here is an example :
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class DataMaker {
public static void main(final String args[]) throws IOException {
DataMaker dm = new DataMaker();
String file = "D:\\input.txt";
int roll = 1;
String rollnum = null;
String outputfilename = null;
boolean shouldContinue = false;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
do {
rollnum = "file-00" + roll;
outputfilename = "D:\\output\\" + rollnum + ".txt";
shouldContinue = dm.fillFile(outputfilename, br, 200);
roll++;
} while (shouldContinue);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private boolean fillFile(final String outputfilename, final BufferedReader reader, final int limit)
throws IOException {
boolean result = false;
String line = null;
BufferedWriter fbw = null;
int temp = 0;
try {
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(outputfilename, true), "UTF-8");
fbw = new BufferedWriter(writer);
while (temp < limit && ((line = reader.readLine()) != null)) {
temp++;
fbw.write(line);
fbw.newLine();
}
// abort if we didn't manage to read the "limit" number of lines
result = (temp == limit);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
fbw.close();
}
return result;
}
}
I have a program that reads in a file using a filename specified by the user.
All file contents must be read and stored in the array. I seem to have done the IO Correctly besides this error. I understand what the error is but not sure how to correct.
EDIT: The array is already defined in the file.
Zoo.java:284: error: incompatible types: String cannot be converted to
Animals
animals[ j ] = bufferedReader.readLine();
Here is my code for the readFile Submodule:
public String readFile(Animals[] animals)
{
Scanner sc = new Scanner(System.in);
String nameOfFile, stringLine;
FileInputStream fileStream = null;
BufferedReader bufferedReader;
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
nameOfFile = sc.nextLine();
try
{
constructed = true;
fileStream = new FileInputStream(nameOfFile);
bufferedReader = new BufferedReader(new InputStreamReader(fileStream));
while((stringLine = bufferedReader.readLine()) != null)
{
for(int j = 0; j < animals.length; j++)
{
animals[j] = bufferedReader.readLine();
}
}
fileStream.close();
}
catch(IOException e)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in file processing: " + e.getMessage();
}
}
Thanks for the help.
animals is array of Animals, but bufferedReader.readLine() reads line. You should convert it to Animal. I don't see definition of your class Animals, but, I think, there should be constructor that takes String as argument.
So, If i'm right, you should basically write:
animals[j] = new Animals(bufferedReader.readLine());
Lots of problems in your code. Starting with the method's input. Also reading from file.
public static void main(String[] args) {
// TODO code application logic here
for(String entry : readFile())
{
System.out.println(entry);
}
}
static public String[] readFile()
{
Scanner sc = new Scanner(System.in);
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
String nameOfFile = sc.nextLine();
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(nameOfFile))); )
{
//constructed = true; why?
String stringLine;
ArrayList<String> arraylist = new ArrayList();
while((stringLine = bufferedReader.readLine()) != null)
{
arraylist.add(stringLine);
}
return arraylist.toArray(new String[0]);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
You should not use available(). It gives no guarantees what so ever. From the API docs of available():
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
How about using Scanner? I think using Scanner is easier
private static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Read more about Java IO here
If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
// Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
// Uncomment the line below if you want to skip the fist line (e.g if headers)
// line = br.readLine();
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
} catch (IOException e) {
System.out.println("ERROR: unable to read file " + file);
e.printStackTrace();
}
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..
The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0
In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
List<String> list = null;
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
//The way that I read integer numbers from a file is...
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(new File("cards.txt"));
int times = input.nextInt();
for(int i = 0; i < times; i++)
{
int numbersFromFile = input.nextInt();
System.out.println(numbersFromFile);
}
}
}
Try this just a little search in Google
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
public class ReadFileUsingFileInputStream {
/**
* #param args
*/
static int ch;
public static void main(String[] args) {
File file = new File("C://text.txt");
StringBuffer stringBuffer = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
while((ch = fileInputStream.read())!= -1){
stringBuffer.append((char)ch);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File contents :");
System.out.println(stringBuffer);
}
}
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}