writing in text file in java - java

I have a text file that contained a large number of words, and i want to divide the words by writing ** for every 4 words.
What i did until now is adding the first ** ( the first 4 words) and I have some difficulties in putting the other stars.
here is my code until now (I am using java)
import java.io.*;
public class Insert {
public static void main(String args[]){
try {
INSERT In = new INSERT();
int tc=4;
In.insertStringInFile (new File("D:/Users//im080828/Desktop/Souad/project/reduction/weight/outdata/d.txt"), tc, "**");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void insertStringInFile(File inFile, int lineno, String lineToBeInserted)
throws Exception {
// temp file
File outFile = new File("$$$$$$$$.tmp");
// input
FileInputStream fis = new FileInputStream(inFile);
BufferedReader in = new BufferedReader
(new InputStreamReader(fis));
// output
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(lineToBeInserted);
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();
inFile.delete();
outFile.renameTo(inFile);
}
}
Please.. give me some ideas
Thanks :)

When you do if (i == lineno) you only get true if (i==4), so your behavior is normal. You need to use the modulo operator if ((i % lineno) == 0) to get a star every for lines.
http://www.dreamincode.net/forums/topic/273783-the-use-of-the-modulo-operator/

Related

Java compressing a .txt file

I am currently trying to write a program which reads in a compressed file which is written in bits or 0s and 1s, and convert them in to strings of 0s and 1s.
The School provided a class and method for reading 1 bit and converting that in to a character char. So to read and convert one bit to a char, all i need to do is type in my code:
char oneBit = inputFile.readBit();
in my main method.
How do I get my program to read over every bit within the compressed file and convert them to char? using the .readBit method? And how would I convert all the char 0s and 1s in to strings of 0s and 1s?
The readBit method:
public char readBit() {
char c = 0;
if (bitsRead == 8)
try {
if (in.available() > 0) { // We have not reached the end of the
// file
buffer = (char) in.read();
bitsRead = 0;
} else
return 0;
} catch (IOException e) {
System.out.println("Error reading from file ");
System.exit(0); // Terminate the program
}
// return next bit from the buffer; bit is converted first to char
if ((buffer & 128) == 0)
c = '0';
else
c = '1';
buffer = (char) (buffer << 1);
++bitsRead;
return c;
}
where in is the input file.
Try using this resource
Sample implementation.
public class BitAnswer {
final static int RADIX = 10;
public static void main(String[] args) {
BitInputStream bis = new BitInputStream("<file_name>");
int result = bis.readBit();
while( result != -1 ) {
System.out.print(Character.forDigit(result, RADIX));
result = bis.readBit();
}
System.out.println("\nAll bits read!");
}
}
public void compress(){
String inputFileName = "c://tmp//content.txt";
String outputFileName = "c://tmp//compressedContent.txt";
FileOutputStream fos = null;
StringBuilder sb = new StringBuilder();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
OutputStream outputStream= null;
try (BufferedReader br = new BufferedReader(new FileReader(new File(inputFileName)))) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
outputStream = new DeflaterOutputStream(byteArrayOutputStream); // GZIPOutputStream(byteArrayOutputStream) - use if you want unix .gz format
outputStream.write(sb.toString().getBytes());
String compressedText = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
fos=new FileOutputStream(outputFileName);
fos.write(compressedText.getBytes());
System.out.println("done compress");
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
if (outputStream != null) {
outputStream.close();
}
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
if(fos != null){
fos.close();
}
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("closed streams !!! ");
}
}

Read from source file and split the contents into two other separate files

My goal is that I wish to read from a file with the name "input.txt", which has 10 lines of text, and then write 5 lines from the original into two other files with the names "test1.txt" and "test2.txt". I'm using the following code, but it is not working - please help me.
import java.util.Scanner;
import java.io.*;
public class main {
public static void main (String args[]) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader (new FileReader("bin/input.txt"));
File file = new File("bin/test2.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("bin/test.txt"));
Scanner sc = new Scanner (br);
int i = 0;
while (sc.hasNextLine()){
sc.nextLine();
i++;
System.out.print(i);
int n = (i+1)/2;
System.out.print("\n"+n);
writer.write(sc.nextLine().toString());
writer.newLine();
if (n==5){
writer.close();
}
}
if (sc != null){
sc.close();
}
}
}
this will read from single file and splitting content into two file.
int count = 0;
BufferedReader br = null;
FileWriter fileWriter1 = new FileWriter("G:\\test1.txt");
FileWriter fileWriter2 = new FileWriter("G:\\test2.txt");
try {
String currentLine;
br = new BufferedReader(new FileReader("G:\\input.txt"));
while ((currentLine = br.readLine()) != null) {
count++;
if (count <= 5) {
fileWriter1.write(currentLine + "\n");
} else {
fileWriter2.write(currentLine + "\n");
}
}
} finally {
if (br != null) {
br.close();
}
fileWriter1.close();
fileWriter2.close();
}
Create two BufferedWriter instead of one with two files and then follow the below procedure:
count <- 0
while scanner hasNextLine
do
string line <- scanner's next Line
if (count > 4) {
writer2.write line
} else {
writer1.write line
}
count <- count + 1
done
finally close all three resources.

fileinputstream to read a given file in a particular order and store in byte[] array

I want to develop a program in java wherein the program reads a file using FileInputStream and then separates all the commas(,) and stores the rest of the values in a byte[] array.
for eg.
if my file "a.txt" contains 1,2,3,-21,-44,56,35,11
i want the program to read this file and store the data in a byte array which will contain
byte[] b{1,2,3,-21,-44,56,35,11}.
i have tried to read the file using FileInputStream.read() but after comparing the character for a comma it points to the next character.
can anyone help me out with the code.
import java.io.*;
class a
{
public static void main(String args[])
{
FileInputStream fis;
int inputSize;
try {
fis = new FileInputStream("New.txt");
inputSize = fis.available();
for(int i=0;i<inputSize;i++)
{
if(fis.read()!=44)
System.out.print((char)fis.read());
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
this might help you out:
private static final String DELIM = ",";
public static void main(String args[]) throws Exception {
// ...
// read the file content line by line with BufferedReader
String line = "5,37,2,-7";
String splitted[] = line.split(DELIM);
byte[] result = new byte[splitted.length];
for (int n = 0; n < splitted.length; ++n) {
result[n] = Byte.parseByte(splitted[n]);
}
System.out.println(Arrays.toString(result));
}
Here's how you can process your file line-by-line:
FileInputStream fis = ...;
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
// process the String line
}
if(fis.read()!=44)
System.out.print((char)fis.read());
You call read() twice, so 2 characters will be read and your code prints only the second character. That's why you are wondering about
but after comparing the character for a comma it points to the next
character
That gives the clou:
int readChar;
if((readChar = fis.read()) != 44)
System.out.print((char)readChar);

How to Compare 1 and 0 and are they equal? with using filereader

I'm trying to wraite a Java program that reads input in text file and compares 1s to 0s. The result is equal when the frequency of 1s are equal to the frequency of 0s.
Example:
Input.txt
1100
100
101
10
Output.txt
Equal!
Not Equal!
Not Equal!
Equal
This is the code I'm working with:
package automata;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader freader = new FileReader("Input.txt");
BufferedReader br = new BufferedReader(freader);
try
{
String s="";
while((s = br.readLine()) != null)
{
int count = 0;
for(int i = 0 ; i < s.length() ; i++)
{
if(s.charAt(i) == '0') count++;
else if(s.charAt(i) == '1') count--;
}
if(count == 0) System.out.print("Equal!\n");
else System.out.print("Not Equal! \n");
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
That's how I'd do it.
import java.io.*;
public class TestFile
{
public TestFile()
{
File inputFile = new File("input.txt"),
outputFile = new File("output.txt");
try
{
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String s;
while((s = br.readLine()) != null)
{
int count = 0;
for(int i = 0 ; i < s.length() ; i++)
{
if(s.charAt(i) == '0') count++;
else if(s.charAt(i) == '1') count--;
}
if(count == 0) bw.append("Equal!\n");
else bw.append("Not Equal! \n");
}
br.close();
bw.close();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
new TestFile();
}
}
If you iterate over every character of each line,
you could count the ones or zeros and compare the result to the half of the length on the complete string.
you could use a counter initialized to zero and count one up for every one and one down for every zero, so you would have it zero on equal number of ones and zeros
Aditionally, if you get a really big amount of data (lots of lines and very long lines) it may make sense to check regulary if a line can be equal before you reach it's end (if you have 1001 ones on a 2000 charater line, you don't need to check any more and saved 999 itertions).

Read data from a text file using Java

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);
}
}
}
}

Categories