啥也不说,直接上程序吧,嘻嘻。。。。。。。。
一、公共类
点击(此处)折叠或打开
-
package com.ruozedata.scalawroks
-
-
import java.io.{FileSystem => _, _}
-
import org.apache.hadoop.fs._
-
import scala.collection.mutable.ListBuffer
-
import org.apache.hadoop.fs.{FileSystem, Path}
-
-
object ScalaToHDFSUtils {
-
-
def isDir(fs : FileSystem, dirName : String) : Boolean = {
-
fs.isDirectory(new Path(dirName))
-
}
-
-
def isDir(fs : FileSystem, dirName : Path) : Boolean = {
-
fs.isDirectory(dirName)
-
}
-
-
def isFile(fs : FileSystem, fileName : String) : Boolean = {
-
fs.isFile(new Path(fileName))
-
}
-
-
def isFile(fs : FileSystem, fileName : Path) : Boolean = {
-
fs.isFile(fileName)
-
}
-
-
def createFile(fs : FileSystem, fileName : String) : Boolean = {
-
fs.createNewFile(new Path(fileName))
-
}
-
-
def createFile(fs : FileSystem, name : Path) : Boolean = {
-
fs.createNewFile(name)
-
}
-
-
def createFolder(fs : FileSystem, folderName : String) : Boolean = {
-
fs.mkdirs(new Path(folderName))
-
}
-
-
def createFolder(fs : FileSystem, folderName : Path) : Boolean = {
-
fs.mkdirs(folderName)
-
}
-
-
def exists(fs : FileSystem, name : String) : Boolean = {
-
fs.exists(new Path(name))
-
}
-
-
def exists(fs : FileSystem, name : Path) : Boolean = {
-
fs.exists(name)
-
}
-
-
def rename(fs : FileSystem, srcPath : String, distPath : String) = {
-
fs.rename( new Path( srcPath ), new Path( distPath ) )
-
}
-
-
def move(fs : FileSystem, srcPath : String, distPath : String) = {
-
fs.rename( new Path( srcPath ), new Path( distPath ) )
-
}
-
-
class MyPathFilter extends PathFilter {
-
override def accept(path: Path): Boolean = true
-
}
-
-
def listFiles(fs : FileSystem, fullName : String, holder : ListBuffer[String],
-
flgFile : Boolean = false) : ListBuffer[String] = {
-
-
val filesStatus = fs.listStatus(new Path(fullName), new MyPathFilter)
-
-
for(status <- filesStatus){
-
val filePath : Path = status.getPath
-
if(isFile(fs,filePath))
-
holder += filePath.toString
-
else {
-
if(flgFile==true)
-
listFiles(fs, filePath.toString, holder)
-
}
-
}
-
holder
-
}
-
-
def copyFile(fs : FileSystem, source: String, target: String): Unit = {
-
-
val sourcePath = new Path(source)
-
val targetPath = new Path(target)
-
-
if(!exists(fs, targetPath))
-
createFile(fs, targetPath)
-
-
val inputStream : FSDataInputStream = fs.open(sourcePath)
-
val outputStream : FSDataOutputStream = fs.create(targetPath)
-
transport(inputStream, outputStream)
-
}
-
-
def transport(inputStream : InputStream, outputStream : OutputStream): Unit ={
-
val buffer = new Array[Byte](64 * 1000)
-
var len = inputStream.read(buffer)
-
try {
-
while (len != -1) {
-
outputStream.write(buffer, 0, len)
-
len = inputStream.read(buffer)
-
}
-
outputStream.flush()
-
} catch {
-
case e : IOException => {
-
e.printStackTrace
-
}
-
} finally {
-
inputStream.close()
-
outputStream.close()
-
}
-
}
-
-
def readFiles(fs : FileSystem, source: String, values: ListBuffer[String]) : ListBuffer[String] = {
-
val sourcePath = new Path(source)
-
val inputStream : FSDataInputStream = fs.open(sourcePath)
-
var bufferedReader: BufferedReader = new BufferedReader(new InputStreamReader(inputStream))
-
var lineTxt : String = bufferedReader.readLine()
-
-
try {
-
while (lineTxt != null) {
-
values.append(lineTxt)
-
lineTxt = bufferedReader.readLine()
-
}
-
values
-
} finally {
-
if (bufferedReader != null) {
-
bufferedReader.close()
-
}
-
if (inputStream != null) {
-
inputStream.close()
-
}
-
}
-
}
-
}
二、移动文件类
点击(此处)折叠或打开
-
package com.ruozedata.scalawroks
-
-
import java.io.IOException
-
import java.net.URI
-
import java.text.SimpleDateFormat
-
import java.util.Date
-
-
import org.apache.hadoop.fs._
-
import org.apache.hadoop.conf.Configuration
-
-
import scala.collection.mutable.ListBuffer
-
-
object ScalaToHDFSApp extends App {
-
val conf = new Configuration()
-
var fs: FileSystem = null
-
-
val sourcePath = "/ruozedata/" // 打包jar时,可以取args(0)值
-
val targetPath = "/ruozedata/scala/" // 打包jar时,可以取args(1)值
-
val uriPath = "hdfs://192.168.137.130:9000/" // 打包jar时,可以取args(2)值
-
-
// 新文件名
-
var newFileName = ""
-
-
// 文件序号
-
var fSeq = 1
-
-
// 设置访问HDFS用户
-
System.setProperty("HADOOP_USER_NAME", "hadoop")
-
-
try {
-
fs = FileSystem.get(new URI(uriPath), conf)
-
-
val holder : ListBuffer[String] = new ListBuffer[String]
-
-
// 获指定目录中文件列表(如果为true则级联查找文件,如果为false则只查找当前目录文件)。默认值:false
-
val paths : List[String] = ScalaToHDFSUtils.listFiles(fs, sourcePath, holder).toList
-
-
for(path <- paths) {
-
// 拼接新文件名
-
newFileName = dateToStr + fSeq.toString + ".txt"
-
// 文件序号+1
-
fSeq += 1
-
// 复制文件到指定目录
-
ScalaToHDFSUtils.copyFile(fs, sourcePath + new Path(path).getName, targetPath + newFileName)
-
}
-
} catch {
-
case e : IOException => {
-
e.printStackTrace
-
}
-
} finally {
-
if (fs != null) {
-
fs.close()
-
}
-
}
-
-
def dateToStr(): String = {
-
// 获取系统日期时间,转为字符串年月日时分格式
-
val date = new Date
-
val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm")
-
var newTmpFileName = dateFormat.format(date) + "-"
-
newTmpFileName
-
}
-
}
三、读取文件,并计算,最张存到MyQL数据库中
-
package com.ruozedata.scalawroks
-
-
import java.io.IOException
-
import java.net.URI
-
import java.sql.{Connection, DriverManager}
-
-
import org.apache.hadoop.conf.Configuration
-
import org.apache.hadoop.fs.{FileSystem, Path}
-
-
import scala.collection.mutable.ListBuffer
-
-
object ScalacReadHDFSApp extends App {
-
val conf = new Configuration()
-
val sourcePath = "/ruozedata/scala/" // 打包jar时,可以取args(0)值
-
val uriPath = "hdfs://192.168.137.130:9000/" // 打包jar时,可以取args(1)值
-
val holder: ListBuffer[String] = new ListBuffer[String]
-
val readHolder: ListBuffer[String] = new ListBuffer[String]
-
-
var fs: FileSystem = null
-
var listBuffer: List[String] = null
-
-
// 设置访问HDFS用户
-
System.setProperty("HADOOP_USER_NAME", "hadoop")
-
-
try {
-
fs = FileSystem.get(new URI(uriPath), conf)
-
-
// 获指定目录中文件列表(如果为true则级联查找文件,如果为false则只查找当前目录文件)。默认值:false
-
val paths : List[String] = ScalaToHDFSUtils.listFiles(fs, sourcePath, holder).toList
-
-
for(path <- paths) {
-
listBuffer = ScalaToHDFSUtils.readFiles(fs, sourcePath + new Path(path).getName, readHolder).toList
-
}
-
-
// 完成WordCount统计
-
val wc = listBuffer.flatMap(_.split("\t")).map((_, 1)).groupBy(_._1).mapValues(_.map(_._2).reduce(_ + _))
-
-
// 调用存入MySQL中
-
insertMySQL(wc)
-
} catch {
-
case e: IOException => {
-
e.printStackTrace
-
}
-
}finally {
-
if (fs != null) {
-
fs.close()
-
}
-
}
-
-
def insertMySQL(wc : Map[String,Int]): Unit = {
-
// connect to the database named "mysql" on the localhost
-
val driver: String = "com.mysql.jdbc.Driver"
-
val url = "jdbc:mysql://192.168.137.130:3306/works"
-
val username = "root"
-
val password = "123456"
-
-
var connection : Connection = null
-
var query = ""
-
-
try{
-
//Class.forName(driver)
-
connection = DriverManager.getConnection(url, username, password)
-
val ps = connection.createStatement()
-
-
for ((key, value) <- wc) {
-
query="insert into wordcounts(words, counts) values('"+key+"' , '"+value+"')"
-
ps.addBatch(query)
-
}
-
-
ps.executeBatch()
-
} catch {
-
case e => e.printStackTrace
-
} finally {
-
connection.close()
-
}
-
}
-
}
四、MySQL表创建
点击(此处)折叠或打开
-
create table wordcounts(words varchar(50), counts varchar(20));
五、Mavne配置(pom.xml)
点击(此处)折叠或打开
六、测试数据
hdfs dfs -ls /ruozedata/scala
Found 3 items
-rw-r--r-- 3 hadoop supergroup 24 2018-02-12 14:48 /ruozedata/scala/201802121449-1.txt
-rw-r--r-- 3 hadoop supergroup 12 2018-02-12 14:48 /ruozedata/scala/201802121449-2.txt
-rw-r--r-- 3 hadoop supergroup 12 2018-02-12 14:48 /ruozedata/scala/201802121449-3.txt
-----------------------------------------------------------------------------------------------------------
hdfs dfs -cat /ruozedata/scala/201802121449-1.txt
hello world
hello worls
hdfs dfs -cat /ruozedata/scala/201802121449-2.txt
hello ruoze
hdfs dfs -cat /ruozedata/scala/201802121449-3.txt
ruoze hello
七、测试结果
注:后续大家有什么好的建议,请提出。
来自@若泽大数据
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31511218/viewspace-2151064/
,如需转载,请注明出处,否则将追究法律责任。