How to write number using fileoutputstream - java

I'm new to java , i need to define counter then write the result in a file
int counter=0;
int resultstweets=0;
fos = new FileOutputStream(new File(
prop.getProperty("PATH_TO_OUTPUT_FILE")));
BufferedReader br = new BufferedReader(new FileReader("path/of/file"));
while ((tweetJson = br.readLine()) != null) {
String result = drpc.execute(TOPOLOGY_NAME, tweetJson);
Status s = null;
try {
s = DataObjectFactory.createStatus(tweetJson);
result = s.getId() + "\t" + s.getText() + "\t" + result;
// this is my counter
resultstweets+=counter;
} catch (TwitterException e) {
LOG.error(e.toString());
}
fos.write(result.getBytes());
fos.write(newLine);
}
fos.write(newLine);
fos.write("Finish: ".getBytes());
fos.write("resultstweets".getBytes());
fos.write(newLine);
// here i write it in the file
fos.write(resultstweets);
but what i got at the end of file
Finish: resultstweets
**\001**459202139258

This method java.io.FileOutputStream.write(byte[] b) you're using in your last line gets a byte array as parameter.
So you should first convert your integer to string and then call getBytes on that:
fos.write(String.valueOf(resultstweets).getBytes());
You can find a proper example of using this method here.

Related

Replace the first line with the longest java text file

i need to replace the first line in the text file with the longest and vice versa. Please tell me what i need to fix and add. At this stage the program looks for the longest line properly. I'm new to Java, I'm sure there is not much to fix, but I do not know what exactly is needed. Also, if possible, help implement the output of the result in a new file.
The code still looks like this:
package pkg;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
public class Main {
static int previousLongLine = 0;
public void printLongLine(HashMap longLineMap) {
Set keyofSet = longLineMap.keySet();
Iterator itr = keyofSet.iterator();
while (itr.hasNext()) {
Integer keys = (Integer) itr.next();
String value = (String) longLineMap.get(keys);
System.out.println("Line Number of Longest line: " + keys
+ "\nLongest line: " + value);
}
}
public static void main(String []args){
// TODO Auto-generated method stub
String fileName = "G:\\colege\\bursa\\Colege\\Programing\\pkg\\File1.txt";
// This will reference one line at a time
String line = null;
int key = 0;
int lineSize = 0, lineNumber = 0;
Main ln = new Main();
HashMap longLineMap = new HashMap();
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
lineNumber++;
lineSize = line.length();
if (lineSize > previousLongLine) {
previousLongLine = lineSize;
longLineMap.clear();
longLineMap.put(lineNumber, line);
}
if(lineNumber == 1){
String old = line;
String newl = old.replaceFirst(old, String.valueOf(previousLongLine));
}
}
//close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
ln.printLongLine(longLineMap);
}
}
You can achieve this with a simple stream operation.
Info on stream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
I've used try-with-resource, which auto-closes the resource after processing has ceased.
Info on try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Read file into an ArrayList
Create another List to hold the sorted elements.
Open a stream on the ArrayList which holds the input data.
Sort the lines into size order. Use Comparator.reverseOrder() for largest to smallest
Using a downstream collector store the output as a new list.
Write sorted list to file.
Reading file:
String inputFile = "files/longestLine.txt";
List<String> lines = new ArrayList<>();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Use a stream to sort the lines into size order.
List<String> sortedLines = lines.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Write to file:
String outputFile = "outputFile.txt";
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFile))) {
for (String line: sortedLines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}

Writer dont writing in file but only create it

Im working on converter. I load file, start reading date from it and creating directories by year, month and day(+ another one dir) in witch ends are those converted text files. Everything is fine while creating those directories but in text files is nothing or only chunk of it.
public static void convertFile(File fileToConvert, File whereToSave, long shift) {
BufferedReader reader = null;
BufferedWriter writer = null;
String oldDate = "";
String newDate = "";
boolean boolDate = true;
try {
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
boolean block = true;
String line = "";
int lineCounter = 0;
while ((line = reader.readLine()) != null) {
if (lineCounter==0) {
block = true;
} else {
block = false;
}
line = line.replaceAll("[^0-9-,:+NaN.]", "");
String[] data = line.split(",");
if (block) {
data[0] = data[0].substring(0, 10) + " " + data[0].substring(10);
data[0] = SimulatorForRealData.timeShift(data[0], shift);
// ====================================================================================
newDate = data[0].substring(0, 4) + " " + data[0].substring(5, 7) + " "
+ data[0].substring(8, 10);
String savingIn = SimulatorForRealData.createDirs(whereToSave.toString(),
data[0].substring(0, 4), data[0].substring(5, 7), data[0].substring(8, 10));
File f = new File(savingIn + "\\" + FILE_NAME + ".log");
if (!newDate.equals(oldDate) && boolDate == false) {
writer.close();
boolDate = true;
} else {
oldDate = newDate;
boolDate = false;
}
writer = new BufferedWriter(new FileWriter(f));
// =====================================================================================
writer.write("<in date=\"" + data[0].substring(0, 10) + "T" + data[0].substring(11)
+ "\" t=\"1\" >\n");
writer.write(data[0] + "\n");
writer.write(0 + " " + 0 + " " + 0 + "\n");
for (int x = 0; x <= 10; x++) {
writer.write("NaN" + " ");
}
writer.write("\n");
for (String s : data) {
if (s.equals(data[0])) {
continue;
}
writer.write(s + ";");
}
writer.write("\n");
} else {
for (String s : data) {
writer.write(s + ";");
}
writer.write("\n");
}
lineCounter++;
if (lineCounter == 118) {
lineCounter = 0;
writer.write("</in>\n\n");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is method where i perform it. Can someone help me. I tried different "writers" and nothing. I have suspicious that it will be problem in closing file but i dont know for sure.
I think you should close every writer you created, not only last one.
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
...
writer = new BufferedWriter(new FileWriter(f));
while ((line = reader.readLine()) != null) {
....
}
writer.close();
}
writer flushes all changes on disk only when buffer is overflowed or it is closed.
I see two main problems:
You create a file every time you read a line. You should put it outside the loop (or loops, if you want only one file)
Always data is written with the same filename. It should have different filenames if you make a file for every file read.

BufferedReader - count lines containing a string

I am using a .txt file that contains: "Hello world\nHow are you doing this day?" I want to count whether a line contains a string or not, as well as the total number of lines. I use:
File file = new File(file_Path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i=0;
int j=0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("o")) { //<----------
i++;
}
}
System.out.print("Lines containing the string: " + i + " of total lines " + j-1);
As I run and test line.contains("o"), it prints 2 lines containing "o", which is correct as well as 2 total lines. As I run line.contains("world"), it prints 0 lines which is wrong but gives 2 lines total. But what do I do wrong?
I tested it with a StringReader,
String str = "Hello world\nHow are you doing this day?";
StringReader sr = new StringReader(str);
try {
BufferedReader br = new BufferedReader(sr);
String line;
int i = 0;
int j = 0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("world")) { // <----------
i++;
}
}
System.out
.println("Lines containing the string: " + i
+ " of total lines " + j);
} catch (Exception e) {
e.printStackTrace();
}
Your file contents must not be what you think because I get
Lines containing the string: 1 of total lines 2
As the others answers and comments, I also think you may not be reading the file you think you are... (Relax it happens to everyone from time to time)
But, also it could be the encoder of the file or the version of the jdk you have, maybe if you could answer:
What did you use to create the file?
What OS you are running
this?
What JDK are you using?
It could clarify what may have happened
Just for you to know, I ran the same code you have using jdk8 and worked fine for me.
As follows the test I did:
1) I put your code in a function:
int countLines(String filename, String wording) {
File file = new File(filename);
String line;
int rowsWithWord = 0;
int totalRows = 0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
totalRows++;
if (line.contains(wording)) {
rowsWithWord++;
}
}
} catch (IOException e) {
System.out.println("Error Counting: " + e.getMessage());
}
System.out.println(String.format("Found %s rows in %s total rows", rowsWithWord, totalRows));
return rowsWithWord;
}
2) and ran the following unit test
#Test
public void testFile() {
try (FileWriter fileWriter = new FileWriter(new File("C:\\TEMP\\DELETE\\Hello.txt"));
BufferedWriter writer = new BufferedWriter(fileWriter)) {
writer.write("Hello world\nHow are you doing this day?");
} catch (IOException e) {
System.out.println("Error writing... " + e);
}
int countO = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "o");
Assert.assertEquals("It did not find 2 lines with the letters = o", 2, countO);
int countWorld = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "world");
Assert.assertEquals("It did not find 1 line with the word = world", 1, countWorld);
}
And I got the expected result:
Found 2 rows in 2 total rows
Found 1 rows in 2 total rows

Buffered Output Writing to File Wrong

I can't figure it out. I'm trying to write out text from my program. It's suppose to a word count program. Show me the number of lines, characters, word count. Then I display the results along with the word the user is searching for and that line.
(i.e. searching java)
line 5: the island of java contains Java
line 9: I love to drink java
It's not displaying text. Its displaying like heiroglyphics.
Line 2: DN{c�<���\$H�Uz�X����h4[����bA.�D��Ja�8^)|��k�ˠ����<Τ���QJ�����P˒��nI"�(��vc�Bi�"&�/�|qI�W6{pa�0��[���[M��;�FU�!}4�x�����{�-��(����V�k#�We֭Tʺ
Line 3: �N�U �������Ӣ ͇�?�
Line 4: Ӻ鬵�P��D<�}L>��o�V�Ex���Q|�)�'��g�I�B�3b�(�"3�T�7��� �=��s�g�F�;KN���r��_�� ʺ:�� �B�ۢ�s��sP����[6��; �� PK ! ��� N _rels/.rels �(�
public void readFromFile(String filename)
{
LineNumberReader lineNumberReader = null;
try {
lineNumberReader = new LineNumberReader(new FileReader(filename));
String line = null;
BufferedWriter output = new BufferedWriter(new FileWriter("output.txt"));
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
Scanner scan = new Scanner(new File("test.txt"));
while ((line = lineNumberReader.readLine()) != null)
{
line = scan.nextLine();
if(line.indexOf(find) >= -1)
{
output.write("Line " + lineNumberReader.getLineNumber() +
": " + line);
output.newLine();
}
}// end of while
output.close();
} // end of try
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally {
try {
if (lineNumberReader != null)
{
lineNumberReader.close();
}
} // end of try
catch (IOException ex)
{
ex.printStackTrace();
}
}// end of finally
} // end of function
I don't get why you are doing this :
while ((line = lineNumberReader.readLine()) != null)
{
line = scan.nextLine();
if(line.indexOf(find) >= -1)
{
output.write("Line " + lineNumberReader.getLineNumber() +
": " + line);
output.newLine();
}
}// end of while
instead of this :
while ((line = lineNumberReader.readLine()) != null)
{
if(line.indexOf(find) >= -1)
{
output.write("Line " + lineNumberReader.getLineNumber() +
": " + line);
output.newLine();
}
}// end of while
You don't need 2 readers for this. And I don't understand why one of the reader is reading in a final file and the other one is reading from a file which name is coming from arg
The default OS encoding is used as set in System.getProperty("file.encoding").
You can explicitly pick one.
final String encoding = "UTF-16LE"; // Or "Cp1252" or "UTF-8"
lineNumberReader = new LineNumberReader(new InputStreamReader(new FileInputStream(filename), encoding));
...
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"), encoding));
...
Scanner scan = new Scanner(new File("test.txt", encoding));

How to zip long string into file and retrieve it?

I am trying to zip a long string into a file and to retrieve it.
The following code does not work. What it retrieves is gibberish.
public static void main(String args[]) {
try {
// Creating base for data
StringBuilder sbb = new StringBuilder();
for (int i=0;i<1000;i++)
sbb.append("ùertyty!|").append(Integer.toString(i));
File FileAll = new File(".\\All.data");
FileAll.createNewFile();
// Zipping into file
DeflaterOutputStream g = new DeflaterOutputStream(
new FileOutputStream(FileAll));
OutputStreamWriter osw = new OutputStreamWriter(g);
String base = sbb.toString();
osw.write(base);
osw.close();
FileInputStream ALL_FIS = new FileInputStream(FileAll);
// Re-reading from file
DeflaterInputStream dis = new DeflaterInputStream(ALL_FIS);
InputStreamReader isr = new InputStreamReader(dis);
StringBuilder sb = new StringBuilder();
char[] c = new char[1000];
int count = isr.read(c);
while ( count != -1 ) {
sb.append(c, 0, count);
count = isr.read(c);
}
isr.close();
String retr = sb.toString();
System.out.println("Are equal: " + retr.equals(base));
System.out.println("Base: " + base);
System.out.println("Retr: " + retr);
} catch (IOException e) {
System.err.println(e.toString());
}
}
What am I doing wrong?
P.S.: It seems like DeflaterInputStream does not do its job and returns the content of the file as is.
You need to use a InflaterInputStream (which decompresses) instead of a DeflaterInputStream
http://download.oracle.com/javase/1.5.0/docs/api/java/util/zip/InflaterInputStream.html

Categories

Resources