I have the following problem I want to read a file and shift each letter down by 3 positions in the alphabet. The caesar cipher works correctly and I can print it, but whenever I am trying to pass it on to a new file with PrintWriter the file remains empty.
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public static char[] encrypt (int offset, char [] charArray) {
char [] cryptArray = new char [charArray.length];
for (int i = 0; i < charArray.length; i++) {
int crypt = (charArray[i] + offset);
cryptArray[i] = (char) (crypt);
}
return cryptArray;
}
public static void main(String[] args) {
String text = "";
StringBuilder convert = new StringBuilder();
try {
File file = new File ("C:\\PATH\\file.txt");
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
text = input.nextLine();
convert = new StringBuilder (text);
char [] arr = text.toCharArray();
char [] newArr = encrypt(3, arr);
for (int i = 0; i < newArr.length; i++) {
convert.append(newArr[i]).toString();
}
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// write file
File outFile = new File ("C:\\PATH\\newfile.txt");
PrintWriter printer = new PrintWriter (outFile);
printer.print(convert);
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
remove convert = new StringBuilder (text); in your loop. It's overwriting your data in the previous loop
Related
Here is the CSV file I am using:
B00123,55
B00783,35
B00898,67
I need to read and store the first value entered in the file e.g. B00123 and store it into an array. A user can add to the file so it is not a fixed number of records.
So far, I have tried this code:
public class ArrayReader
{
static String xStrPath;
static double[][] myArray;
static void setUpMyCSVArray()
{
myArray = new double [4][5];
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "src\\marks.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] InArray = InputLine.split(",");
//copy the content of the inArray to the myArray
for (int x = 0; x < myArray.length; x++)
{
myArray[Rowc][x] = Double.parseDouble(InArray[x]);
}
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (int Rowc = 0; Rowc < 1; Rowc++)
{
for (int Colc = 0; Colc < 5; Colc++)
{
System.out.println(myArray[Rowc][Colc] + " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
This loops round the file but doesn't not populate the array with any data. The outcome is:
****** Setup Array ******
[[D#42a57993
0.0
0.0
0.0
0.0
0.0
There is actually a NumberFormatException happening when in the first row when trying to convert the ID to Double. So I revised the program and it works for me.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ArrayReader
{
static String xStrPath;
static Map<String,Double> myArray = new HashMap<>();
static void setUpMyCSVArray()
{
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "/Users/admin/Downloads/mark.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] inArray = InputLine.split(",");
//copy the content of the inArray to the myArray
myArray.put(inArray[0], Double.valueOf(inArray[1]));
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
System.out.println(e);
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (String key : myArray.keySet()) {
System.out.println(key + " = " + myArray.get(key));
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
Output:
the code can't reader anything ,you file path incorrect.give it absoulte file path.
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
I use opencsv library to read from csv.
import com.opencsv.CSVReader;
public class CSV {
private static String file = <filepath>;
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
list.add(line[0]);
}
Object[] myArray = list.toArray();
System.out.println(myArray.length);
System.out.println(myArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output printed as below
3
B00123
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'm working on a Java program in which I must read the contents of a file and then print each lines reverse. For example the text:
Public Class Helloprinter
Public static void
would print the following after running my reverse program:
retnirPolleh ssalc cilbup
diov citats cilbup
Here's what I got so far:
public static void main(String[] args) throws FileNotFoundException {
// Prompt for the input and output file names
ArrayList<String> list = new ArrayList<String>();
//String reverse = "";
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
String aString = "";
while(in.hasNextLine())
{
String line = in.nextLine();
list.add(line);
}
in.close();
for(int i = 0; i <list.size(); i++)
{
aString = list.get(i);
aString = new StringBuffer(aString).reverse().toString();
out.printf("%s", " " + aString);
}
out.close();
}
}
EDIT:
With Robert's posting it helped put me in the right direction. The problem is that with that is that it doesn't keep the lines.
Public Class Helloprinter
Public static void
becomes after running my program:
retnirPolleh ssalc cilbup diov citats cilbup
it needs to keep the line layout the same. so it should be:
retnirPolleh ssalc cilbup
diov citats cilbup
Your problem is in the line
out.printf("%s", " " + aString);
This doesn't output a newline. I'm also not sure why you are sticking a space in there.
It should be either:
out.println( aString );
Or
out.printf("%s%n", aString);
In your last loop why don't you just iterate through the list backwards? So:
for(int i = 0; i <list.size(); i++)
Becomes:
for(int i = list.size() - 1; i >=0; i--)
It seems like you already know how to read a file, so then call this method for each line.
Note, this is recursion and it's probably not the most efficient but it's simple and it does what you want.
public String reverseString(final String s) {
if (s.length() == 0)
return s;
// move chahctrachter at current position and then put it at the end of the string.
return reverseString(s.substring(1)) + s.charAt(0);
}
Just use a string builder. You were on the right trail. Probably just needed a little help. There is no "one way" to do anything, but you could try something like this:
Note: Here is my output: retnirPolleh ssalc cilbup diov citats cilbup
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;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
ArrayList<String> myReverseList = null;
System.out.println("Input file: \n");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
System.out.println("Output file: \n");
String outputFileName = input.nextLine();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String text = null;
myReverseList = new ArrayList<String>();
StringBuilder sb = null;
try {
while ((text = br.readLine()) != null) {
sb = new StringBuilder();
for (int i = text.length() - 1; i >= 0; i--) {
sb.append(text.charAt(i));
}
myReverseList.add(sb.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFileName), "utf-8"));
for (String s : myReverseList) {
writer.write("" + s + "\n");
}
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
}
I previously asked a question about converting a CSV file to 2D array in java. I completely rewrote my code and it is almost reworking. The only problem I am having now is that it is printing backwards. In other words, the columns are printing where the rows should be and vice versa. Here is my code:
int [][] board = new int [25][25];
String line = null;
BufferedReader stream = null;
ArrayList <String> csvData = new ArrayList <String>();
stream = new BufferedReader(new FileReader(fileName));
while ((line = stream.readLine()) != null) {
String[] splitted = line.split(",");
ArrayList<String> dataLine = new ArrayList<String>(splitted.length);
for (String data : splitted)
dataLine.add(data);
csvData.addAll(dataLine);
}
int [] number = new int [csvData.size()];
for(int z = 0; z < csvData.size(); z++)
{
number[z] = Integer.parseInt(csvData.get(z));
}
for(int q = 0; q < number.length; q++)
{
System.out.println(number[q]);
}
for(int i = 0; i< number.length; i++)
{
System.out.println(number[i]);
}
for(int i=0; i<25;i++)
{
for(int j=0;j<25;j++)
{
board[i][j] = number[(j*25) + i];
}
}
Basically, the 2D array is supposed to have 25 rows and 25 columns. When reading the CSV file in, I saved it into a String ArrayList then I converted that into a single dimension int array. Any input would be appreciated. Thanks
so you want to read a CSV file in java , then you might wanna use OPEN CSV
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CsvFileReader {
public static void main(String[] args) {
try {
System.out.println("\n**** readLineByLineExample ****");
String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] col = null;
while ((col = csvReader.readNext()) != null)
{
System.out.println(col[0] );
//System.out.println(col[0]);
}
csvReader.close();
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae+" : error here");
}catch (FileNotFoundException e)
{
System.out.println("asd");
e.printStackTrace();
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
}
}
and you can get the related jar file from here
someone can help me with code?
How to search in text file any word and count how many it were repeated?
For example test.txt:
hi
hola
hey
hi
bye
hoola
hi
And if I want to know how many times are repeated in test.txt word "Hi" program must say "3 times repeated"
I hope you understood what I want, thank you for answers.
public int countWord(String word, File file) {
int count = 0;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(word))
count++;
}
return count;
}
HashMap h=new HashMap();
FileInputStream fin=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
String n;
while((n=br.readLine())!=null)
{
if(h.containsKey(n))
{
int i=(Integer)h.get(n);
h.put(n,(i+1));
}
else
h.put(n, 1);
}
now iterate through this map to get the count for each word using each word as a key to the map values
Apache Commons - StringUtils.countMatches()
Use MultiSet collection from google guava library.
Multiset<String> wordsMultiset = HashMultiset.create();
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
wordsMultiset.add(scanner.nextLine());
}
for(Multiset.Entry<String> entry : wordsMultiset ){
System.out.println("Word : "+entry.getElement()+" count -> "+entry.getCount());
}
package File1;
import java.io.BufferedReader;
import java.io.FileReader;
public class CountLineWordsDuplicateWords {
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br =null;
String [] stringArray;
int counLine = 0;
int arrayLength ;
String s="";
String stringLine="";
try{
fr = new FileReader("F:/Line.txt");
br = new BufferedReader(fr);
while((s = br.readLine()) != null){
stringLine = stringLine + s;
stringLine = stringLine + " ";/*Add space*/
counLine ++;
}
System.out.println(stringLine);
stringArray = stringLine.split(" ");
arrayLength = stringArray.length;
System.out.println("The number of Words is "+arrayLength);
/*Duplicate String count code */
for (int i = 0; i < arrayLength; i++) {
int c = 1 ;
for (int j = i+1; j < arrayLength; j++) {
if(stringArray[i].equalsIgnoreCase(stringArray[j])){
c++;
for (int j2 = j; j2 < arrayLength; j2++) {
stringArray[j2] = stringArray[j2+1];
arrayLength = arrayLength - 1;
}
}//End of If block
}//End of Inner for block
System.out.println("The "+stringArray[i]+" present "+c+" times .");
}//End of Outer for block
System.out.println("The number of Line is "+counLine);
System.out.println();
fr.close();
br.close();
}catch (Exception e) {
e.printStackTrace();
}
}//End of main() method
}//End of class CountLineWordsDuplicateWords
package somePackage;
public static void main(String[] args) {
String path = ""; //ADD YOUR PATH HERE
String fileName = "test2.txt";
String testWord = "Macbeth"; //CHANGE THIS IF YOU WANT
int tLen = testWord.length();
int wordCntr = 0;
String file = path + fileName;
boolean check;
try{
FileInputStream fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\\s+");
for(String w : lineWords){
//first see if the word is as least as long as the testWord
if(w.length() >= tLen){
/*
1) grab the specific word, minus whitespace
2) check to see whether the first part of it having same length
as testWord is equivalent to testWord, ignoring case
*/
String word = w.substring(0,tLen).trim();
if(word.equalsIgnoreCase(testWord)){
wordCntr++;
}
}
}
}
}
System.out.println("total is: " + wordCntr);
//Close the input stream
br.close();
} catch(Exception e){
e.printStackTrace();
}
}
public class Wordcount
{
public static void main(String[] args)
{
int count=0;
String str="hi this is is is line";
String []s1=str.split(" ");
for(int i=0;i<=s1.length-1;i++)
{
if(s1[i].equals("is"))
{
count++;
}
}
System.out.println(count);
}
}
You can read text file line by line. I assume that each line can contain more than one word. For each line, you call:
String[] words = line.split(" ");
for(int i=0; i<words.length; i++){
if(words[i].equalsIgnoreCase(searhedWord))
count++;
}
try using java.util.Scanner.
public int countWords(String w, String fileName) {
int count = 0;
Scanner scanner = new Scanner(inputFile);
scanner.useDelimiter("[^a-zA-Z]"); // non alphabets act as delimeters
String word = scanner.next();
if (word.equalsIgnoreCase(w))
count++;
return count;
}
Try it this way with Pattern and Matcher.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Dem {
public static void main(String[] args){
try {
File f = new File("d://My.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = new String();
while((s=br.readLine())!=null){
s = s + s;
}
int count = 0;
Pattern pat = Pattern.compile("it*");
Matcher mat = pat.matcher(s);
while(mat.find()){
if(mat.find()){
mat.start();
count++;
}
}
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String ar[])throws Exception
BufferedReader br=new BufferedReader(new FileReader("c:/file.txt"));
System.out.println("enter the string which you search");
Scanner ob=new Scanner(System.in);
String str=ob.next();
String str1="",str2="";
int count=0;
while((str1=br.readLine())!=null)
{
str2 +=str1;
}
int index = str2.indexOf(str);
while (index != -1) {
count++;
str2 = str2.substring(index + 1);
index = str2.indexOf(str);
}
System.out.println("Number of the occures="+count);
}
}
package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception{
BufferedReader bf= new BufferedReader(new FileReader("src/test.txt"));
Scanner sc = new Scanner(System.in);
String W=sc.next();
//String regex ="[\\w"+W+"]";
int count=0;
//Pattern p = Pattern.compile();
String line=bf.readLine();
String s[];
do
{
s=line.split(" ");
for(String a:s)
{
if(a.contains(W))
count++;
}
line=bf.readLine();
}while(line!=null);
System.out.println(count);
}
}
public int occurrencesOfHi()
{
String newText = Text.replace("Hi","");
return (Text.length() - newText.length())/2;
}